Advertisement
EconomicSerg

Sieve

Oct 21st, 2020 (edited)
320
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.73 KB | None | 0 0
  1. -- sieve.lua
  2. -- the sieve of Eratosthenes programmed with coroutines
  3. -- typical usage: lua -e N=500 sieve.lua | column
  4.  
  5. -- generate all the numbers from 2 to n
  6. function gen (n)
  7.   return coroutine.wrap(function ()
  8.     for i=2,n do coroutine.yield(i) end
  9.   end)
  10. end
  11.  
  12. -- filter the numbers generated by `g', removing multiples of `p'
  13. function filter (p, g)
  14.   return coroutine.wrap(function ()
  15.     for n in g do
  16.       if n%p ~= 0 then coroutine.yield(n) end
  17.     end
  18.   end)
  19. end
  20.  
  21. N=N or 500      -- from command line
  22. x = gen(N)      -- generate primes up to N
  23. while 1 do
  24.   local n = x()     -- pick a number until done
  25.   if n == nil then break end
  26.   print(n)      -- must be a prime number
  27.   x = filter(n, x)  -- now remove its multiples
  28. end
  29.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement