1 -- the sieve of of Eratosthenes programmed with coroutines
2 -- typical usage: lua -e N=1000 sieve.lua | column
4 -- generate all the numbers from 2 to n
6 return coroutine
.wrap(function ()
7 for i
=2,n
do coroutine
.yield(i
) end
11 -- filter the numbers generated by `g', removing multiples of `p'
12 function filter (p
, g
)
13 return coroutine
.wrap(function ()
16 if n
== nil then return end
17 if math
.mod(n
, p
) ~= 0 then coroutine
.yield(n
) end
22 N
=N
or 1000 -- from command line
23 x
= gen(N
) -- generate primes up to N
25 local n
= x() -- pick a number until done
26 if n
== nil then break end
27 print(n
) -- must be a prime number
28 x
= filter(n
, x
) -- now remove its multiples