11# Sieve of Eratosthenes: an efficient algorithm to compute all prime numbers up to n.
22# It repeatedly marks multiples of each prime as non-prime, starting from 2.
33# This method is suitable for n up to about 10**7 on typical hardware.
4- # Wikipedia URl - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
4+ # Wikipedia URL - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
55
6- def sieve_of_erastosthenes ( n ) :
6+ def sieve_of_eratosthenes ( n : int ) -> list [ int ] :
77 """
8- Compute all prime numbers up to and including n using the Sieve of Eratosthenes.
9- Parameters
10- ----------
11- n : int
12- Upper bound (inclusive) of the range in which to find prime numbers.
13- Expected to be a non-negative integer. If n < 2 the function returns an empty list.
14- Returns
15- -------
16- list[int]
17- A list of primes in ascending order that are <= n.
8+ Compute all prime numbers up to and including n using the Sieve of Eratosthenes.
9+
10+ Parameters
11+ ----------
12+ n : int
13+ Upper bound (inclusive) of the range in which to find prime numbers.
14+ Expected to be a non-negative integer. If n < 2 the function returns an empty list.
15+
16+ Returns
17+ -------
18+ list[int]
19+ A list of primes in ascending order that are <= n.
20+
21+ Examples
22+ --------
23+ >>> sieve_of_eratosthenes(10)
24+ [2, 3, 5, 7]
25+ >>> sieve_of_eratosthenes(1)
26+ []
27+ >>> sieve_of_eratosthenes(2)
28+ [2]
29+ >>> sieve_of_eratosthenes(20)
30+ [2, 3, 5, 7, 11, 13, 17, 19]
1831 """
32+ if n < 2 :
33+ return []
1934
20-
21- #Boolean list to track prime status of numbers
2235 prime = [True ] * (n + 1 )
2336 p = 2
24-
25- # Main Algorithm
2637 while p * p <= n :
2738 if prime [p ]:
28-
29- # All multiples of p will be non-prime hence delcare them False.
30-
3139 for i in range (p * p , n + 1 , p ):
3240 prime [i ] = False
3341 p += 1
3442
35- # Store all primes.
36- result = []
37- for p in range (2 , n + 1 ):
38- if prime [p ]:
39- result .append (p )
40-
41- return result
43+ return [p for p in range (2 , n + 1 ) if prime [p ]]
44+
4245
4346if __name__ == "__main__" :
44- n = 35
45- result = sieve_of_erastosthenes (n )
46- for num in result :
47- print (num , end = ' ' )
47+ print (sieve_of_eratosthenes (35 ))
0 commit comments