Skip to content

Commit e74dd2d

Browse files
committed
Updated sieve_of_eratosthenes.py
Edited according to unit test and changed the loop to list comprehension.
1 parent 9a3a4c7 commit e74dd2d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

misc/sieve_of_eratosthenes.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
3+
Implementation of Sieve of Eratosthenes algorithm to generate all the primes upto N.
4+
5+
Reference : https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
6+
7+
Algorithm :
8+
* We have a list of numbers from 1 to N.
9+
* Initially, all the numbers are marked as primes.
10+
* We go to every prime number in the list (<= N ^ 1/2) and mark all the multiples of this prime number which are bigger than the number itself as non-primes.
11+
12+
"""
13+
14+
from math import sqrt,ceil
15+
16+
def calculate_primes(n):
17+
bool_array = [True] * (n+1)
18+
bool_array[0] = False
19+
bool_array[1] = False
20+
upper_bound = ceil(sqrt(n))
21+
for i in range(2,upper_bound):
22+
if bool_array[i]:
23+
for j in range(i*i,n+1,i):
24+
bool_array[j] = False
25+
prime_array = [i for i in range(n+1) if bool_array[i]]
26+
return prime_array
27+
28+
if __name__ == "__main__":
29+
print(calculate_primes(50))

0 commit comments

Comments
 (0)