Skip to content

Commit 6506531

Browse files
committed
Create sieve_of_eratosthenes.py
Created a new folder of primality under Python/math and added a suitable algorithm
1 parent e2a78d4 commit 6506531

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Sieve of Eratosthenes: an efficient algorithm to compute all prime numbers up to n.
2+
# It repeatedly marks multiples of each prime as non-prime, starting from 2.
3+
# This method is suitable for n up to about 10**7 on typical hardware.
4+
5+
def sieve_of_erastosthenes(n):
6+
7+
#Boolean list to track prime status of numbers
8+
prime = [True] * (n + 1)
9+
p = 2
10+
11+
# Main Algorithm
12+
while p * p <= n:
13+
if prime[p]:
14+
15+
# All multiples of p will be non-prime hence delcare them False.
16+
17+
for i in range(p * p, n + 1, p):
18+
prime[i] = False
19+
p += 1
20+
21+
# Store all primes.
22+
result = []
23+
for p in range(2, n + 1):
24+
if prime[p]:
25+
result.append(p)
26+
27+
return result
28+
29+
if __name__ == "__main__":
30+
n = 35
31+
result = sieve_of_erastosthenes(n)
32+
for num in result:
33+
print(num, end=' ')

0 commit comments

Comments
 (0)