aboutsummaryrefslogtreecommitdiff
path: root/libs/lua/test/sieve.lua
diff options
context:
space:
mode:
authorPavel Labath <pavelo@centrum.sk>2011-05-16 10:58:21 (GMT)
committerPavel Labath <pavelo@centrum.sk>2011-11-01 09:52:45 (GMT)
commit3c1d7bb1c521e824dfa46903fd4014722d0f5a29 (patch)
treeb9d8ab1f95aa608cbef817550ccc4bd42534dcd6 /libs/lua/test/sieve.lua
parent2223c879bf41d2b4f40fa43db478ba1bce8523de (diff)
downloadfluxbox_paul-3c1d7bb1c521e824dfa46903fd4014722d0f5a29.zip
fluxbox_paul-3c1d7bb1c521e824dfa46903fd4014722d0f5a29.tar.bz2
Add lua as an internal library in libs/lua
Diffstat (limited to 'libs/lua/test/sieve.lua')
-rw-r--r--libs/lua/test/sieve.lua29
1 files changed, 29 insertions, 0 deletions
diff --git a/libs/lua/test/sieve.lua b/libs/lua/test/sieve.lua
new file mode 100644
index 0000000..0871bb2
--- /dev/null
+++ b/libs/lua/test/sieve.lua
@@ -0,0 +1,29 @@
1-- the sieve of of Eratosthenes programmed with coroutines
2-- typical usage: lua -e N=1000 sieve.lua | column
3
4-- generate all the numbers from 2 to n
5function gen (n)
6 return coroutine.wrap(function ()
7 for i=2,n do coroutine.yield(i) end
8 end)
9end
10
11-- filter the numbers generated by `g', removing multiples of `p'
12function filter (p, g)
13 return coroutine.wrap(function ()
14 while 1 do
15 local n = g()
16 if n == nil then return end
17 if math.mod(n, p) ~= 0 then coroutine.yield(n) end
18 end
19 end)
20end
21
22N=N or 1000 -- from command line
23x = gen(N) -- generate primes up to N
24while 1 do
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
29end