[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Problem with sieve.lua test program
- From: Wim Couwenberg <w.couwenberg@...>
- Date: Tue, 05 Apr 2005 21:13:47 +0200
I just tried to run the sieve.lua test program (sieve of Eratosthenes
via coroutines)
It runs fine with N=1000 but exits prematurely on larger args.
Maybe a bit OT but it can be instructive to benchmark sieve.lua
(performance- and memory-wise) against the even simpler coroutine-less
version below.
--
Wim
-- the sieve of of Eratosthenes programmed without coroutines
-- typical usage: lua -e N=1000 sieve.lua | column
-- generate all the numbers from 2 to n
function gen (n)
local i = 1
return function()
if i < n then
i = i + 1
return i
end
end
end
-- filter the numbers generated by `g', removing multiples of `p'
function filter (p, g)
return function()
while 1 do
local n = g()
if n == nil then return end
if math.mod(n, p) ~= 0 then return n end
end
end
end
N=N or 1000 -- from command line
x = gen(N) -- generate primes up to N
while 1 do
local n = x() -- pick a number until done
if n == nil then break end
print(n) -- must be a prime number
x = filter(n, x) -- now remove its multiples
end