- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathsieve_of_eratosthenes.py
66 lines (50 loc) · 1.68 KB
/
sieve_of_eratosthenes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Sieve of Eratosthones
The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or
equal to a given value.
Illustration:
https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
"""
from __future__ importannotations
importmath
defprime_sieve(num: int) ->list[int]:
"""
Returns a list with all prime numbers up to n.
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve(9)
[2, 3, 5, 7]
>>> prime_sieve(2)
[2]
>>> prime_sieve(1)
[]
"""
ifnum<=0:
msg=f"{num}: Invalid input, please enter a positive integer."
raiseValueError(msg)
sieve= [True] * (num+1)
prime= []
start=2
end=int(math.sqrt(num))
whilestart<=end:
# If start is a prime
ifsieve[start] isTrue:
prime.append(start)
# Set multiples of start be False
foriinrange(start*start, num+1, start):
ifsieve[i] isTrue:
sieve[i] =False
start+=1
forjinrange(end+1, num+1):
ifsieve[j] isTrue:
prime.append(j)
returnprime
if__name__=="__main__":
print(prime_sieve(int(input("Enter a positive integer: ").strip())))