2019-10-22 17:13:48 +00:00
|
|
|
"""
|
2019-10-21 18:10:19 +00:00
|
|
|
Sieve of Eratosthenes
|
|
|
|
|
2023-01-02 01:10:59 +00:00
|
|
|
Input: n = 10
|
2020-09-30 08:38:00 +00:00
|
|
|
Output: 2 3 5 7
|
2019-10-21 18:10:19 +00:00
|
|
|
|
2023-01-02 01:10:59 +00:00
|
|
|
Input: n = 20
|
2020-09-30 08:38:00 +00:00
|
|
|
Output: 2 3 5 7 11 13 17 19
|
2019-10-21 18:10:19 +00:00
|
|
|
|
2020-01-18 12:24:33 +00:00
|
|
|
you can read in detail about this at
|
2019-10-21 18:10:19 +00:00
|
|
|
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
2019-10-22 17:13:48 +00:00
|
|
|
"""
|
|
|
|
|
2019-10-21 18:10:19 +00:00
|
|
|
|
2023-01-02 01:10:59 +00:00
|
|
|
def prime_sieve_eratosthenes(num: int) -> list[int]:
|
2019-10-21 18:10:19 +00:00
|
|
|
"""
|
2023-01-02 01:10:59 +00:00
|
|
|
Print the prime numbers up to n
|
2020-01-18 12:24:33 +00:00
|
|
|
|
2019-10-21 18:10:19 +00:00
|
|
|
>>> prime_sieve_eratosthenes(10)
|
2023-01-02 01:10:59 +00:00
|
|
|
[2, 3, 5, 7]
|
2019-10-21 18:10:19 +00:00
|
|
|
>>> prime_sieve_eratosthenes(20)
|
2023-01-02 01:10:59 +00:00
|
|
|
[2, 3, 5, 7, 11, 13, 17, 19]
|
|
|
|
>>> prime_sieve_eratosthenes(2)
|
|
|
|
[2]
|
|
|
|
>>> prime_sieve_eratosthenes(1)
|
|
|
|
[]
|
|
|
|
>>> prime_sieve_eratosthenes(-1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: Input must be a positive integer
|
2019-10-21 18:10:19 +00:00
|
|
|
"""
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2023-01-02 01:10:59 +00:00
|
|
|
if num <= 0:
|
|
|
|
raise ValueError("Input must be a positive integer")
|
|
|
|
|
|
|
|
primes = [True] * (num + 1)
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2023-01-02 01:10:59 +00:00
|
|
|
p = 2
|
2019-10-21 18:10:19 +00:00
|
|
|
while p * p <= num:
|
2020-01-18 12:24:33 +00:00
|
|
|
if primes[p]:
|
2019-10-22 17:13:48 +00:00
|
|
|
for i in range(p * p, num + 1, p):
|
2019-10-21 18:10:19 +00:00
|
|
|
primes[i] = False
|
2019-10-22 17:13:48 +00:00
|
|
|
p += 1
|
2019-10-21 18:10:19 +00:00
|
|
|
|
2023-01-02 01:10:59 +00:00
|
|
|
return [prime for prime in range(2, num + 1) if primes[prime]]
|
2019-10-21 18:10:19 +00:00
|
|
|
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2019-10-21 18:10:19 +00:00
|
|
|
if __name__ == "__main__":
|
2020-09-10 08:31:26 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2023-01-02 01:10:59 +00:00
|
|
|
user_num = int(input("Enter a positive integer: ").strip())
|
|
|
|
print(prime_sieve_eratosthenes(user_num))
|