File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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 = ' ' )
You can’t perform that action at this time.
0 commit comments