forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsieve_of_sundaram.py
More file actions
48 lines (36 loc) · 1.04 KB
/
sieve_of_sundaram.py
File metadata and controls
48 lines (36 loc) · 1.04 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Sieve of Sundaram - Alternative prime number algorithm.
Discovered by S. P. Sundaram in 1934.
"""
from typing import List
def sieve_of_sundaram(limit: int) -> List[int]:
"""
Find all prime numbers up to limit using Sieve of Sundaram.
>>> sieve_of_sundaram(30)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
>>> sieve_of_sundaram(10)
[2, 3, 5, 7]
>>> sieve_of_sundaram(2)
[]
"""
if limit <= 2:
return []
n = (limit - 1) // 2
marked = [False] * (n + 1)
for i in range(1, n + 1):
j = i
while i + j + 2 * i * j <= n:
marked[i + j + 2 * i * j] = True
j += 1
primes = [2]
for i in range(1, n + 1):
if not marked[i]:
primes.append(2 * i + 1)
return primes
if __name__ == "__main__":
print("Sieve of Sundaram Demo")
print("-" * 20)
for limit in [10, 30, 50]:
primes = sieve_of_sundaram(limit)
print(f"Primes up to {limit}: {primes}")
print(f"Found {len(primes)} primes")