|
1 | 1 | """
|
2 | 2 | Sieve of Eratosthenes
|
3 | 3 |
|
4 |
| -Input : n =10 |
| 4 | +Input: n = 10 |
5 | 5 | Output: 2 3 5 7
|
6 | 6 |
|
7 |
| -Input : n = 20 |
| 7 | +Input: n = 20 |
8 | 8 | Output: 2 3 5 7 11 13 17 19
|
9 | 9 |
|
10 | 10 | you can read in detail about this at
|
11 | 11 | https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
12 | 12 | """
|
13 | 13 |
|
14 | 14 |
|
15 |
| -def prime_sieve_eratosthenes(num): |
| 15 | +def prime_sieve_eratosthenes(num: int) -> list[int]: |
16 | 16 | """
|
17 |
| - print the prime numbers up to n |
| 17 | + Print the prime numbers up to n |
18 | 18 |
|
19 | 19 | >>> prime_sieve_eratosthenes(10)
|
20 |
| - 2,3,5,7, |
| 20 | + [2, 3, 5, 7] |
21 | 21 | >>> prime_sieve_eratosthenes(20)
|
22 |
| - 2,3,5,7,11,13,17,19, |
| 22 | + [2, 3, 5, 7, 11, 13, 17, 19] |
| 23 | + >>> prime_sieve_eratosthenes(2) |
| 24 | + [2] |
| 25 | + >>> prime_sieve_eratosthenes(1) |
| 26 | + [] |
| 27 | + >>> prime_sieve_eratosthenes(-1) |
| 28 | + Traceback (most recent call last): |
| 29 | + ... |
| 30 | + ValueError: Input must be a positive integer |
23 | 31 | """
|
24 | 32 |
|
25 |
| - primes = [True for i in range(num + 1)] |
26 |
| - p = 2 |
| 33 | + if num <= 0: |
| 34 | + raise ValueError("Input must be a positive integer") |
| 35 | + |
| 36 | + primes = [True] * (num + 1) |
27 | 37 |
|
| 38 | + p = 2 |
28 | 39 | while p * p <= num:
|
29 | 40 | if primes[p]:
|
30 | 41 | for i in range(p * p, num + 1, p):
|
31 | 42 | primes[i] = False
|
32 | 43 | p += 1
|
33 | 44 |
|
34 |
| - for prime in range(2, num + 1): |
35 |
| - if primes[prime]: |
36 |
| - print(prime, end=",") |
| 45 | + return [prime for prime in range(2, num + 1) if primes[prime]] |
37 | 46 |
|
38 | 47 |
|
39 | 48 | if __name__ == "__main__":
|
40 | 49 | import doctest
|
41 | 50 |
|
42 | 51 | doctest.testmod()
|
43 |
| - num = int(input()) |
44 | 52 |
|
45 |
| - prime_sieve_eratosthenes(num) |
| 53 | + user_num = int(input("Enter a positive integer: ").strip()) |
| 54 | + print(prime_sieve_eratosthenes(user_num)) |
0 commit comments