-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathex01.lua
More file actions
28 lines (27 loc) · 700 Bytes
/
ex01.lua
File metadata and controls
28 lines (27 loc) · 700 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
-- Example 1. Sieve of Eratosthenes
function sieve(n)
-- Construct initial {2..n} table.
local is_prime = {}
for i = 2, n do
is_prime[i] = true
end
-- Strike out all existing multiples of primes.
for i = 2, math.sqrt(n) do
if is_prime[i] then
for j = i^2, n, i do
is_prime[j] = false
end
end
end
-- Construct the final primes list.
local primes = {}
for i = 2, n do
if is_prime[i] then
primes[#primes + 1] = i
end
end
return primes
end
--8<----------------------------------------------------------------------------
print(table.unpack(sieve(30)))
--8<----------------------------------------------------------------------------