2019-07-26 10:25:38 +00:00
|
|
|
"""
|
|
|
|
Sieve of Eratosthones
|
|
|
|
|
2020-06-16 08:09:19 +00:00
|
|
|
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
|
2019-07-26 10:25:38 +00:00
|
|
|
Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
|
|
|
|
|
|
|
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
|
|
|
|
Also thanks Dmitry (https://github.com/LizardWizzard) for finding the problem
|
|
|
|
"""
|
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
import math
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2019-07-26 10:25:38 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
def sieve(n):
|
2019-07-26 10:25:38 +00:00
|
|
|
"""
|
|
|
|
Returns a list with all prime numbers up to n.
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2019-07-26 10:25:38 +00:00
|
|
|
>>> sieve(50)
|
|
|
|
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
|
|
|
|
>>> sieve(25)
|
|
|
|
[2, 3, 5, 7, 11, 13, 17, 19, 23]
|
|
|
|
>>> sieve(10)
|
|
|
|
[2, 3, 5, 7]
|
|
|
|
>>> sieve(9)
|
|
|
|
[2, 3, 5, 7]
|
|
|
|
>>> sieve(2)
|
|
|
|
[2]
|
|
|
|
>>> sieve(1)
|
|
|
|
[]
|
|
|
|
"""
|
|
|
|
|
2020-05-22 06:10:11 +00:00
|
|
|
l = [True] * (n + 1) # noqa: E741
|
2018-10-19 12:48:28 +00:00
|
|
|
prime = []
|
|
|
|
start = 2
|
2019-07-10 20:09:24 +00:00
|
|
|
end = int(math.sqrt(n))
|
2019-07-26 10:25:38 +00:00
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
while start <= end:
|
2019-07-26 10:25:38 +00:00
|
|
|
# If start is a prime
|
2019-07-10 20:09:24 +00:00
|
|
|
if l[start] is True:
|
2018-10-19 12:48:28 +00:00
|
|
|
prime.append(start)
|
2019-07-26 10:25:38 +00:00
|
|
|
|
|
|
|
# Set multiples of start be False
|
2019-07-10 20:09:24 +00:00
|
|
|
for i in range(start * start, n + 1, start):
|
|
|
|
if l[i] is True:
|
2018-10-19 12:48:28 +00:00
|
|
|
l[i] = False
|
2019-07-26 10:25:38 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
start += 1
|
2019-07-10 20:09:24 +00:00
|
|
|
|
|
|
|
for j in range(end + 1, n + 1):
|
|
|
|
if l[j] is True:
|
2018-10-19 12:48:28 +00:00
|
|
|
prime.append(j)
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
return prime
|
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2019-07-21 06:16:28 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
print(sieve(int(input("Enter n: ").strip())))
|