Python/maths/sieve_of_eratosthenes.py

28 lines
613 B
Python
Raw Normal View History

"""Sieve of Eratosthones."""
2018-10-19 12:48:28 +00:00
import math
2018-10-19 12:48:28 +00:00
def sieve(n):
"""Sieve of Eratosthones."""
l = [True] * (n + 1)
2018-10-19 12:48:28 +00:00
prime = []
start = 2
end = int(math.sqrt(n))
while start <= end:
if l[start] is True:
2018-10-19 12:48:28 +00:00
prime.append(start)
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
start += 1
for j in range(end + 1, n + 1):
if l[j] is True:
2018-10-19 12:48:28 +00:00
prime.append(j)
2018-10-19 12:48:28 +00:00
return prime
if __name__ == "__main__":
print(sieve(int(input("Enter n: ").strip())))