[mypy] math/sieve_of_eratosthenes: Add type hints (#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 <dhruvmanila@gmail.com>
This commit is contained in:
Joyce 2020-11-23 13:37:42 +08:00 committed by GitHub
parent f2c1f98a23
commit 03e7f37329
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,54 +8,58 @@ https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animat
Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich) doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
Also thanks Dmitry (https://github.com/LizardWizzard) for finding the problem Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
""" """
import math import math
from typing import List
def sieve(n): def prime_sieve(num: int) -> List[int]:
""" """
Returns a list with all prime numbers up to n. Returns a list with all prime numbers up to n.
>>> sieve(50) >>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> sieve(25) >>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23] [2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> sieve(10) >>> prime_sieve(10)
[2, 3, 5, 7] [2, 3, 5, 7]
>>> sieve(9) >>> prime_sieve(9)
[2, 3, 5, 7] [2, 3, 5, 7]
>>> sieve(2) >>> prime_sieve(2)
[2] [2]
>>> sieve(1) >>> prime_sieve(1)
[] []
""" """
l = [True] * (n + 1) # noqa: E741 if num <= 0:
raise ValueError(f"{num}: Invalid input, please enter a positive integer.")
sieve = [True] * (num + 1)
prime = [] prime = []
start = 2 start = 2
end = int(math.sqrt(n)) end = int(math.sqrt(num))
while start <= end: while start <= end:
# If start is a prime # If start is a prime
if l[start] is True: if sieve[start] is True:
prime.append(start) prime.append(start)
# Set multiples of start be False # Set multiples of start be False
for i in range(start * start, n + 1, start): for i in range(start * start, num + 1, start):
if l[i] is True: if sieve[i] is True:
l[i] = False sieve[i] = False
start += 1 start += 1
for j in range(end + 1, n + 1): for j in range(end + 1, num + 1):
if l[j] is True: if sieve[j] is True:
prime.append(j) prime.append(j)
return prime return prime
if __name__ == "__main__": if __name__ == "__main__":
print(sieve(int(input("Enter n: ").strip()))) print(prime_sieve(int(input("Enter a positive integer: ").strip())))