# Sieve of Eratosthenes iterator

**URL:** <https://discourse.julialang.org/t/sieve-of-eratosthenes-iterator/121512>\
**Category:** New to Julia\
**Tags:** python, generator, iterators, julia\
**Created:** [October 20, 2024, 5:57pm UTC](https://discourse.julialang.org/t/sieve-of-eratosthenes-iterator/121512 "2024-10-20T17:57:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Brinkhuis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brinkhuis/32/18752_2.png) [@Brinkhuis](https://discourse.julialang.org/u/Brinkhuis)\
**Post date:** [October 20, 2024, 5:57pm UTC](https://discourse.julialang.org/t/sieve-of-eratosthenes-iterator/121512/1 "2024-10-20T17:57:37Z")

</div>

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`.

```julia
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

```

---

<div class="post-metadata">

**Author:** ![sgaure](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sgaure/32/14779_2.png) [@sgaure](https://discourse.julialang.org/u/sgaure)\
**Post date:** [October 20, 2024, 7:56pm UTC](https://discourse.julialang.org/t/sieve-of-eratosthenes-iterator/121512/2 "2024-10-20T19:56:40Z")

</div>

You can either make an iterator, i.e. define `Base.iterate` for a suitable `struct`, as in [Interfaces · The Julia Language](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-iteration), With less boilerplate you can make a coroutine with the help of a `Channel`, as in [Asynchronous Programming · The Julia Language](https://docs.julialang.org/en/v1/manual/asynchronous-programming/#Communicating-with-Channels). Instead of `yield` in the loop, you do a `put!` on a channel, which you can `take!` from elsewhere.
