Skip to content

Commit f30f609

Browse files
committed
refactored sieve of eratosthenes
1 parent 99b71d3 commit f30f609

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

misc/sieve_of_eratosthenes.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,25 @@
11
"""
2-
32
Implementation of Sieve of Eratosthenes algorithm to generate all the primes upto N.
43
54
Reference : https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
65
76
Algorithm :
87
* We have a list of numbers from 1 to N.
98
* 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-
9+
* We go to every prime number in the list (<= N ^ 1/2) and mark all the multiples
10+
of this prime number which are bigger than the number itself as non-primes.
1211
"""
1312

1413
from math import sqrt,ceil
1514

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
15+
def generate_primes(n):
16+
bool_array = [False, False] + [True] * n # start with all values as True, except 0 and 1
17+
for i in range(2, int(ceil(sqrt(n)))): # only go to till square root of n
18+
if bool_array[i]: # if the number is marked as prime
19+
for j in range(i*i,n+1,i): # iterate through all its multiples
20+
bool_array[j] = False # and mark them as False
21+
primes = [i for i in range(n+1) if bool_array[i]] # return all numbers which are marked as True
22+
return primes
2723

2824
if __name__ == "__main__":
29-
print(calculate_primes(50))
25+
print(generate_primes(50))

0 commit comments

Comments
 (0)