Skip to content

Commit 22d6f5c

Browse files
committed
Faster & Optimized sieve_of_eratosthenes.py
1 parent a71618f commit 22d6f5c

1 file changed

Lines changed: 16 additions & 20 deletions

File tree

maths/sieve_of_eratosthenes.py

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
Sieve of Eratosthones
2+
Sieve of Eratosthenes
33
44
The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or
55
equal to a given value.
@@ -9,10 +9,10 @@
99
1010
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
1111
Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
12+
optimized by : Sumit Nayak (https://github.com/Sumit210106/)
1213
"""
1314

1415
from __future__ import annotations
15-
1616
import 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

6561
if __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

Comments
 (0)