Skip to content

Commit 1c41186

Browse files
authored
Optimize Sieve of Eratosthenes (#20)
1 parent e823618 commit 1c41186

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed
Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,27 @@
11
describe("Sieve of Eratosthenes", function()
22
local sieve = require("math.prime.sieve_of_eratosthenes")
33
local check_primality = require("math.prime.is_prime")
4+
5+
local function check_sieve(n)
6+
local sieve_result = sieve(n)
7+
assert.equal(n, #sieve_result)
8+
for number, is_prime in ipairs(sieve_result) do
9+
assert.equal(check_primality(number), is_prime)
10+
end
11+
end
12+
413
it("works for small numbers", function()
5-
for n = 1, 5 do
6-
for number, is_prime in ipairs(sieve(n ^ 2 * 1000)) do
7-
assert.equal(check_primality(number), is_prime)
8-
end
14+
for i = 1, 10 do
15+
check_sieve(i)
916
end
17+
check_sieve(24)
18+
check_sieve(25)
19+
check_sieve(26)
20+
check_sieve(1000)
21+
check_sieve(4000)
22+
check_sieve(9000)
23+
check_sieve(16000)
24+
check_sieve(25000)
1025
end)
1126
it("yields the correct count for large numbers", function()
1227
local count = 0
@@ -17,4 +32,9 @@ describe("Sieve of Eratosthenes", function()
1732
end
1833
assert.equal(78498, count)
1934
end)
35+
it("should throw error when input is not positive", function()
36+
assert.has_error(function()
37+
sieve(0)
38+
end)
39+
end)
2040
end)

src/math/prime/sieve_of_eratosthenes.lua

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
return function(
33
n -- number
44
)
5+
assert(n > 0, "n must be positive")
56
local is_prime = { false }
67
for m = 2, n do -- mark as prime
78
is_prime[m] = true
89
end
9-
for m = 2, n / 2 do -- iterate possible primes
10+
for m = 2, math.sqrt(n) do -- iterate possible primes
1011
if is_prime[m] then
11-
for l = 2 * m, n, m do -- iterate multiples
12+
for l = m * m, n, m do -- iterate multiples
1213
is_prime[l] = false -- "cross out" composite
1314
end
1415
end

0 commit comments

Comments
 (0)