diff --git a/maths/prime_sieve_eratosthenes.py b/maths/prime_sieve_eratosthenes.py deleted file mode 100644 index 8d60e48c2140..000000000000 --- a/maths/prime_sieve_eratosthenes.py +++ /dev/null @@ -1,47 +0,0 @@ -# flake8: noqa - -""" -Sieve of Eratosthenes - -Input : n =10 -Output: 2 3 5 7 - -Input : n = 20 -Output: 2 3 5 7 11 13 17 19 - -you can read in detail about this at -https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes -""" - - -def prime_sieve_eratosthenes(num): - """ - print the prime numbers up to n - - >>> prime_sieve_eratosthenes(10) - 2,3,5,7, - >>> prime_sieve_eratosthenes(20) - 2,3,5,7,11,13,17,19, - """ - - primes = [True for i in range(num + 1)] - p = 2 - - while p * p <= num: - if primes[p]: - for i in range(p * p, num + 1, p): - primes[i] = False - p += 1 - - for prime in range(2, num + 1): - if primes[prime]: - print(prime, end=",") - - -if __name__ == "__main__": - import doctest - - doctest.testmod() - num = int(input()) - - prime_sieve_eratosthenes(num) diff --git a/maths/sieve_of_eratosthenes.py b/maths/sieve_of_eratosthenes.py index 3cd6ce0b4d9d..be0a5d4fc629 100644 --- a/maths/sieve_of_eratosthenes.py +++ b/maths/sieve_of_eratosthenes.py @@ -10,9 +10,6 @@ doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich) Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem """ -from __future__ import annotations - -import math def prime_sieve(num: int) -> list[int]: @@ -33,32 +30,34 @@ def prime_sieve(num: int) -> list[int]: [] """ - if num <= 0: - raise ValueError(f"{num}: Invalid input, please enter a positive integer.") + if num < 2: + return [] sieve = [True] * (num + 1) - prime = [] - start = 2 - end = int(math.sqrt(num)) + sieve[0] = sieve[1] = False - while start <= end: - # If start is a prime - if sieve[start] is True: - prime.append(start) + # Do even numbers separately + primes = [2] + for i in range(4, num + 1, 2): + sieve[i] = False - # Set multiples of start be False - for i in range(start * start, num + 1, start): - if sieve[i] is True: - sieve[i] = False + p = 3 + while p * p <= num: + # If p is a prime + if sieve[p] is True: + primes.append(p) - start += 1 + # Set multiples of start be False + for i in range(p * p, num + 1, p): + sieve[i] = False + p += 2 - for j in range(end + 1, num + 1): - if sieve[j] is True: - prime.append(j) + for i in range(p, num + 1, 2): + if sieve[i] is True: + primes.append(i) - return prime + return primes if __name__ == "__main__": - print(prime_sieve(int(input("Enter a positive integer: ").strip()))) + print(prime_sieve(int(input("Get all primes less than or equal to: ").strip())))