Skip to content

Commit f66e62b

Browse files
tianyizheng02Cjkjvfnby
authored andcommitted
Change prime_sieve_eratosthenes.py to return list (TheAlgorithms#8062)
1 parent 669482f commit f66e62b

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

Diff for: maths/prime_sieve_eratosthenes.py

+22-13
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,54 @@
11
"""
22
Sieve of Eratosthenes
33
4-
Input : n =10
4+
Input: n = 10
55
Output: 2 3 5 7
66
7-
Input : n = 20
7+
Input: n = 20
88
Output: 2 3 5 7 11 13 17 19
99
1010
you can read in detail about this at
1111
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
1212
"""
1313

1414

15-
def prime_sieve_eratosthenes(num):
15+
def prime_sieve_eratosthenes(num: int) -> list[int]:
1616
"""
17-
print the prime numbers up to n
17+
Print the prime numbers up to n
1818
1919
>>> prime_sieve_eratosthenes(10)
20-
2,3,5,7,
20+
[2, 3, 5, 7]
2121
>>> 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
2331
"""
2432

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)
2737

38+
p = 2
2839
while p * p <= num:
2940
if primes[p]:
3041
for i in range(p * p, num + 1, p):
3142
primes[i] = False
3243
p += 1
3344

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]]
3746

3847

3948
if __name__ == "__main__":
4049
import doctest
4150

4251
doctest.testmod()
43-
num = int(input())
4452

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

Comments
 (0)