11"""
2- Sieve of Eratosthones
2+ Sieve of Eratosthenes
33
44The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or
55equal to a given value.
99
1010doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
1111Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
12+ optimized by : Sumit Nayak (https://github.com/Sumit210106/)
1213"""
1314
1415from __future__ import annotations
15-
1616import math
1717
1818
@@ -38,29 +38,25 @@ def prime_sieve(num: int) -> list[int]:
3838 msg = f"{ num } : Invalid input, please enter a positive integer."
3939 raise ValueError (msg )
4040
41- sieve = [True ] * (num + 1 )
42- prime = []
43- start = 2
44- end = int (math .sqrt (num ))
45-
46- while start <= end :
47- # If start is a prime
48- if sieve [start ] is True :
49- prime .append (start )
41+ if num < 2 :
42+ return []
5043
51- # Set multiples of start be False
52- for i in range (start * start , num + 1 , start ):
53- if sieve [i ] is True :
54- sieve [i ] = False
44+ sieve = [True ] * (num + 1 )
45+ prime = [2 ]
5546
56- start += 1
47+ # marked all even numbers as non-prime
48+ for i in range (3 , int (math .sqrt (num )) + 1 , 2 ):
49+ if sieve [i ]:
50+ for j in range (i * i , num + 1 , 2 * i ):
51+ sieve [j ] = False
5752
58- for j in range (end + 1 , num + 1 ):
59- if sieve [j ] is True :
60- prime .append (j )
53+ # collect odd primes
54+ for k in range (3 , num + 1 , 2 ):
55+ if sieve [k ]:
56+ prime .append (k )
6157
6258 return prime
6359
6460
6561if __name__ == "__main__" :
66- print (prime_sieve (int (input ("Enter a positive integer: " ).strip ())))
62+ print (prime_sieve (int (input ("Enter a positive integer: " ).strip ())))
0 commit comments