Skip to content

Commit

Permalink
Optimize Sieve of Eratosthenes (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
vil02 authored Dec 3, 2023
1 parent e823618 commit 1c41186
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
28 changes: 24 additions & 4 deletions .spec/math/prime/sieve_of_eratosthenes_spec.lua
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
describe("Sieve of Eratosthenes", function()
local sieve = require("math.prime.sieve_of_eratosthenes")
local check_primality = require("math.prime.is_prime")

local function check_sieve(n)
local sieve_result = sieve(n)
assert.equal(n, #sieve_result)
for number, is_prime in ipairs(sieve_result) do
assert.equal(check_primality(number), is_prime)
end
end

it("works for small numbers", function()
for n = 1, 5 do
for number, is_prime in ipairs(sieve(n ^ 2 * 1000)) do
assert.equal(check_primality(number), is_prime)
end
for i = 1, 10 do
check_sieve(i)
end
check_sieve(24)
check_sieve(25)
check_sieve(26)
check_sieve(1000)
check_sieve(4000)
check_sieve(9000)
check_sieve(16000)
check_sieve(25000)
end)
it("yields the correct count for large numbers", function()
local count = 0
Expand All @@ -17,4 +32,9 @@ describe("Sieve of Eratosthenes", function()
end
assert.equal(78498, count)
end)
it("should throw error when input is not positive", function()
assert.has_error(function()
sieve(0)
end)
end)
end)
5 changes: 3 additions & 2 deletions src/math/prime/sieve_of_eratosthenes.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
return function(
n -- number
)
assert(n > 0, "n must be positive")
local is_prime = { false }
for m = 2, n do -- mark as prime
is_prime[m] = true
end
for m = 2, n / 2 do -- iterate possible primes
for m = 2, math.sqrt(n) do -- iterate possible primes
if is_prime[m] then
for l = 2 * m, n, m do -- iterate multiples
for l = m * m, n, m do -- iterate multiples
is_prime[l] = false -- "cross out" composite
end
end
Expand Down

0 comments on commit 1c41186

Please sign in to comment.