Sieve of Eratosthenes iterator

Brinkhuis
Sun, 20 Oct 2024 17:57:37 +0000
New to Julia

I would like to create an Iterator for prime numbers (I know there is a package Primes). Based on Pythons code for the Sieve of Eratosthenes I coded a function sieve(). sieve(10) returns a vector of the first 10 primes.

What must be done to turn this into en Iterator so that it calculates one prime at a time when you want the next prime?

Thanks for any advice! I’m quite new to Julia and coming from Python I look for an (easy) alternative for generators.

function sieve(n::Int64)::Vector{Int64}

    D = Dict{Int64, Vector{Int64}}()
    P = Vector{Int64}()
    q = 2
    counter = 0

    while counter < n
        if !(q in keys(D))
            D[q * q] = Int64[q] # Vector{Int64}([q])
            push!(P, q)
            counter += 1
        else
            for p in D[q]
                haskey(D, p+q) ? push!(D[p+q], p) : D[p+q] = [p]
            end
            delete!(D, q)
        end
        q += 1
    end
    return P
end

2 posts - 2 participants