Skip to content

Commit ef61a37

Browse files
committed
commit
1 parent 3cea941 commit ef61a37

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

maths/sieve_of_sundaram.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Sieve of Sundaram - Alternative prime number algorithm.
3+
Discovered by S. P. Sundaram in 1934.
4+
"""
5+
6+
from typing import List
7+
8+
9+
def sieve_of_sundaram(limit: int) -> List[int]:
10+
"""
11+
Find all prime numbers up to limit using Sieve of Sundaram.
12+
13+
>>> sieve_of_sundaram(30)
14+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
15+
>>> sieve_of_sundaram(10)
16+
[2, 3, 5, 7]
17+
>>> sieve_of_sundaram(2)
18+
[]
19+
"""
20+
if limit <= 2:
21+
return []
22+
23+
n = (limit - 1) // 2
24+
marked = [False] * (n + 1)
25+
26+
for i in range(1, n + 1):
27+
j = i
28+
while i + j + 2 * i * j <= n:
29+
marked[i + j + 2 * i * j] = True
30+
j += 1
31+
32+
primes = [2]
33+
for i in range(1, n + 1):
34+
if not marked[i]:
35+
primes.append(2 * i + 1)
36+
37+
return primes
38+
39+
40+
41+
if __name__ == "__main__":
42+
print("Sieve of Sundaram Demo")
43+
print("-" * 20)
44+
45+
for limit in [10, 30, 50]:
46+
primes = sieve_of_sundaram(limit)
47+
print(f"Primes up to {limit}: {primes}")
48+
print(f"Found {len(primes)} primes")

0 commit comments

Comments
 (0)