mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 01:00:15 +00:00
Change prime_sieve_eratosthenes.py to return list (#8062)
This commit is contained in:
parent
d29afca93b
commit
7c1d23d448
|
@ -12,34 +12,43 @@ https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def prime_sieve_eratosthenes(num):
|
def prime_sieve_eratosthenes(num: int) -> list[int]:
|
||||||
"""
|
"""
|
||||||
print the prime numbers up to n
|
Print the prime numbers up to n
|
||||||
|
|
||||||
>>> prime_sieve_eratosthenes(10)
|
>>> prime_sieve_eratosthenes(10)
|
||||||
2,3,5,7,
|
[2, 3, 5, 7]
|
||||||
>>> prime_sieve_eratosthenes(20)
|
>>> prime_sieve_eratosthenes(20)
|
||||||
2,3,5,7,11,13,17,19,
|
[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
|
||||||
"""
|
"""
|
||||||
|
|
||||||
primes = [True for i in range(num + 1)]
|
if num <= 0:
|
||||||
p = 2
|
raise ValueError("Input must be a positive integer")
|
||||||
|
|
||||||
|
primes = [True] * (num + 1)
|
||||||
|
|
||||||
|
p = 2
|
||||||
while p * p <= num:
|
while p * p <= num:
|
||||||
if primes[p]:
|
if primes[p]:
|
||||||
for i in range(p * p, num + 1, p):
|
for i in range(p * p, num + 1, p):
|
||||||
primes[i] = False
|
primes[i] = False
|
||||||
p += 1
|
p += 1
|
||||||
|
|
||||||
for prime in range(2, num + 1):
|
return [prime for prime in range(2, num + 1) if primes[prime]]
|
||||||
if primes[prime]:
|
|
||||||
print(prime, end=",")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import doctest
|
import doctest
|
||||||
|
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
num = int(input())
|
|
||||||
|
|
||||||
prime_sieve_eratosthenes(num)
|
user_num = int(input("Enter a positive integer: ").strip())
|
||||||
|
print(prime_sieve_eratosthenes(user_num))
|
||||||
|
|
Loading…
Reference in New Issue
Block a user