Skip to content

Commit 18416c2

Browse files
pikuletdhruvmanila
authored andcommitted
[mypy] math/sieve_of_eratosthenes: Add type hints (TheAlgorithms#2627)
* add type hints to math/sieve * add doctest * math/sieve: remove manual doctest * add check for negative * Update maths/sieve_of_eratosthenes.py * Update sieve_of_eratosthenes.py Co-authored-by: Dhruv Manilawala <[email protected]>
1 parent 94c25c6 commit 18416c2

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

Diff for: maths/sieve_of_eratosthenes.py

+21-17
Original file line numberDiff line numberDiff line change
@@ -8,54 +8,58 @@
88
Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
99
1010
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
1212
"""
1313

1414

1515
import math
16+
from typing import List
1617

1718

18-
def sieve(n):
19+
def prime_sieve(num: int) -> List[int]:
1920
"""
2021
Returns a list with all prime numbers up to n.
2122
22-
>>> sieve(50)
23+
>>> prime_sieve(50)
2324
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
24-
>>> sieve(25)
25+
>>> prime_sieve(25)
2526
[2, 3, 5, 7, 11, 13, 17, 19, 23]
26-
>>> sieve(10)
27+
>>> prime_sieve(10)
2728
[2, 3, 5, 7]
28-
>>> sieve(9)
29+
>>> prime_sieve(9)
2930
[2, 3, 5, 7]
30-
>>> sieve(2)
31+
>>> prime_sieve(2)
3132
[2]
32-
>>> sieve(1)
33+
>>> prime_sieve(1)
3334
[]
3435
"""
3536

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)
3741
prime = []
3842
start = 2
39-
end = int(math.sqrt(n))
43+
end = int(math.sqrt(num))
4044

4145
while start <= end:
4246
# If start is a prime
43-
if l[start] is True:
47+
if sieve[start] is True:
4448
prime.append(start)
4549

4650
# 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
5054

5155
start += 1
5256

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:
5559
prime.append(j)
5660

5761
return prime
5862

5963

6064
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

Comments
 (0)