Skip to content

Instantly share code, notes, and snippets.

@alexandre
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save alexandre/e4eab22155807b0ff587 to your computer and use it in GitHub Desktop.

Select an option

Save alexandre/e4eab22155807b0ff587 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
#!/usr/bin/python3
from math import sqrt
def sieve(limit, limit_list=[]):
'''
Sieve of Eratosthenes - The sieve of Eratosthenes is one of the most
efficient ways to find all of the smaller primes (below 10 million or so).
>>> sieve(30)
[2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
'''
max_num = int(sqrt(limit))
limit_list = [n for n in range(2, limit)]
first_el = limit_list[0]
limit_list = [first_el] + [n for n in limit_list if n % first_el > 0]
return (first_el != max_num and limit_list) or sieve(limit, limit_list)
print(sieve(int(input('the limit: '))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment