diff --git a/maths/sieve_of_eratosthenes.py b/maths/sieve_of_eratosthenes.py index 3923dc3e1612..f935c8d943b2 100644 --- a/maths/sieve_of_eratosthenes.py +++ b/maths/sieve_of_eratosthenes.py @@ -1,5 +1,5 @@ """ -Sieve of Eratosthones +Sieve of Eratosthenes The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value. @@ -9,10 +9,10 @@ doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich) Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem +optimized by : Sumit Nayak (https://github.com/Sumit210106/) """ from __future__ import annotations - import math @@ -38,26 +38,22 @@ def prime_sieve(num: int) -> list[int]: msg = f"{num}: Invalid input, please enter a positive integer." raise ValueError(msg) - sieve = [True] * (num + 1) - prime = [] - start = 2 - end = int(math.sqrt(num)) - - while start <= end: - # If start is a prime - if sieve[start] is True: - prime.append(start) + if num < 2: + return [] - # Set multiples of start be False - for i in range(start * start, num + 1, start): - if sieve[i] is True: - sieve[i] = False - - start += 1 - - for j in range(end + 1, num + 1): - if sieve[j] is True: - prime.append(j) + sieve = [True] * (num + 1) + prime = [2] + + # marked all even numbers as non-prime + for i in range(3, int(math.sqrt(num)) + 1, 2): + if sieve[i]: + for j in range(i * i, num + 1, 2 * i): + sieve[j] = False + + # collect odd primes + for k in range(3, num + 1, 2): + if sieve[k]: + prime.append(k) return prime