sieve.lua 774 B

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