Skip to content

Commit eb55817

Browse files
committed
Add optimized Sieve of Eratosthenes algorithm
1 parent f16e35e commit eb55817

File tree

2 files changed

+61
-47
lines changed

2 files changed

+61
-47
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Optimized Sieve of Eratosthenes: An efficient algorithm to compute all prime numbers up to n.
2+
# This version skips even numbers after 2, improving both memory and time usage.
3+
# It is particularly efficient for larger n (e.g., up to 10**8 on typical hardware).
4+
# Wikipedia URL - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
5+
6+
from math import isqrt
7+
8+
def optimized_sieve(n: int) -> list[int]:
9+
"""
10+
Compute all prime numbers up to and including n using an optimized Sieve of Eratosthenes.
11+
12+
This implementation skips even numbers after 2 to reduce memory and runtime by about 50%.
13+
14+
Parameters
15+
----------
16+
n : int
17+
Upper bound (inclusive) of the range in which to find prime numbers.
18+
Expected to be a non-negative integer. If n < 2 the function returns an empty list.
19+
20+
Returns
21+
-------
22+
list[int]
23+
A list of primes in ascending order that are <= n.
24+
25+
Examples
26+
--------
27+
>>> optimized_sieve(10)
28+
[2, 3, 5, 7]
29+
>>> optimized_sieve(1)
30+
[]
31+
>>> optimized_sieve(2)
32+
[2]
33+
>>> optimized_sieve(30)
34+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
35+
"""
36+
if n < 2:
37+
return []
38+
39+
# Handle 2 separately, then consider only odd numbers
40+
primes = [2] if n >= 2 else []
41+
42+
# Only odd numbers from 3 to n
43+
size = (n - 1) // 2
44+
is_prime = [True] * (size + 1)
45+
limit = isqrt(n)
46+
47+
for i in range((limit - 1) // 2 + 1):
48+
if is_prime[i]:
49+
p = 2 * i + 3
50+
# Start marking from p^2, converted to index
51+
start = (p * p - 3) // 2
52+
for j in range(start, size + 1, p):
53+
is_prime[j] = False
54+
55+
primes.extend(2 * i + 3 for i in range(size + 1) if is_prime[i])
56+
return primes
57+
58+
59+
if __name__ == "__main__":
60+
61+
print(optimized_sieve(50))

maths/primality/sieve_of_eratosthenes.py

Lines changed: 0 additions & 47 deletions
This file was deleted.

0 commit comments

Comments
 (0)