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