|
8 | 8 | Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
9 | 9 |
|
10 | 10 | doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
|
11 |
| -Also thanks Dmitry (https://github.com/LizardWizzard) for finding the problem |
| 11 | +Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem |
12 | 12 | """
|
13 | 13 |
|
14 | 14 |
|
15 | 15 | import math
|
| 16 | +from typing import List |
16 | 17 |
|
17 | 18 |
|
18 |
| -def sieve(n): |
| 19 | +def prime_sieve(num: int) -> List[int]: |
19 | 20 | """
|
20 | 21 | Returns a list with all prime numbers up to n.
|
21 | 22 |
|
22 |
| - >>> sieve(50) |
| 23 | + >>> prime_sieve(50) |
23 | 24 | [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
|
24 |
| - >>> sieve(25) |
| 25 | + >>> prime_sieve(25) |
25 | 26 | [2, 3, 5, 7, 11, 13, 17, 19, 23]
|
26 |
| - >>> sieve(10) |
| 27 | + >>> prime_sieve(10) |
27 | 28 | [2, 3, 5, 7]
|
28 |
| - >>> sieve(9) |
| 29 | + >>> prime_sieve(9) |
29 | 30 | [2, 3, 5, 7]
|
30 |
| - >>> sieve(2) |
| 31 | + >>> prime_sieve(2) |
31 | 32 | [2]
|
32 |
| - >>> sieve(1) |
| 33 | + >>> prime_sieve(1) |
33 | 34 | []
|
34 | 35 | """
|
35 | 36 |
|
36 |
| - l = [True] * (n + 1) # noqa: E741 |
| 37 | + if num <= 0: |
| 38 | + raise ValueError(f"{num}: Invalid input, please enter a positive integer.") |
| 39 | + |
| 40 | + sieve = [True] * (num + 1) |
37 | 41 | prime = []
|
38 | 42 | start = 2
|
39 |
| - end = int(math.sqrt(n)) |
| 43 | + end = int(math.sqrt(num)) |
40 | 44 |
|
41 | 45 | while start <= end:
|
42 | 46 | # If start is a prime
|
43 |
| - if l[start] is True: |
| 47 | + if sieve[start] is True: |
44 | 48 | prime.append(start)
|
45 | 49 |
|
46 | 50 | # Set multiples of start be False
|
47 |
| - for i in range(start * start, n + 1, start): |
48 |
| - if l[i] is True: |
49 |
| - l[i] = False |
| 51 | + for i in range(start * start, num + 1, start): |
| 52 | + if sieve[i] is True: |
| 53 | + sieve[i] = False |
50 | 54 |
|
51 | 55 | start += 1
|
52 | 56 |
|
53 |
| - for j in range(end + 1, n + 1): |
54 |
| - if l[j] is True: |
| 57 | + for j in range(end + 1, num + 1): |
| 58 | + if sieve[j] is True: |
55 | 59 | prime.append(j)
|
56 | 60 |
|
57 | 61 | return prime
|
58 | 62 |
|
59 | 63 |
|
60 | 64 | if __name__ == "__main__":
|
61 |
| - print(sieve(int(input("Enter n: ").strip()))) |
| 65 | + print(prime_sieve(int(input("Enter a positive integer: ").strip()))) |
0 commit comments