|
1 | 1 | """ |
2 | | -
|
3 | 2 | Implementation of Sieve of Eratosthenes algorithm to generate all the primes upto N. |
4 | 3 |
|
5 | 4 | Reference : https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes |
6 | 5 |
|
7 | 6 | Algorithm : |
8 | 7 | * We have a list of numbers from 1 to N. |
9 | 8 | * 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. |
12 | 11 | """ |
13 | 12 |
|
14 | 13 | from math import sqrt,ceil |
15 | 14 |
|
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 |
27 | 23 |
|
28 | 24 | if __name__ == "__main__": |
29 | | - print(calculate_primes(50)) |
| 25 | + print(generate_primes(50)) |
0 commit comments