Skip to content

Commit a06995a

Browse files
ShuLaPycclauss
authored andcommitted
add simple improved Sieve Of Eratosthenes Algorithm (TheAlgorithms#1412)
* add simple improved Sieve Of Eratosthenes Algorithm * added doctests * name changed
1 parent afeb13b commit a06995a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

maths/prime_sieve_eratosthenes.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Sieve of Eratosthenes
3+
4+
Input : n =10
5+
Output : 2 3 5 7
6+
7+
Input : n = 20
8+
Output: 2 3 5 7 11 13 17 19
9+
10+
you can read in detail about this at
11+
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
12+
'''
13+
14+
def prime_sieve_eratosthenes(num):
15+
"""
16+
print the prime numbers upto n
17+
18+
>>> prime_sieve_eratosthenes(10)
19+
2 3 5 7
20+
>>> prime_sieve_eratosthenes(20)
21+
2 3 5 7 11 13 17 19
22+
"""
23+
24+
25+
primes = [True for i in range(num + 1)]
26+
p = 2
27+
28+
while p * p <= num:
29+
if primes[p] == True:
30+
for i in range(p*p, num+1, p):
31+
primes[i] = False
32+
p+=1
33+
34+
for prime in range(2, num+1):
35+
if primes[prime]:
36+
print(prime, end=" ")
37+
38+
if __name__ == "__main__":
39+
num = int(input())
40+
41+
prime_sieve_eratosthenes(num)

0 commit comments

Comments
 (0)