Skip to content

Instantly share code, notes, and snippets.

@basepi
Created May 30, 2011 02:34
Show Gist options
  • Save basepi/998383 to your computer and use it in GitHub Desktop.
Save basepi/998383 to your computer and use it in GitHub Desktop.
Eratosthenes Sieve
def eratosthenes_sieve(n):
# Create a candidate list within which non-primes will be
# marked as None; only candidates below sqrt(n) need be checked.
candidates = list(range(n+1))
fin = int(n**0.5)
# Loop over the candidates, marking out each multiple.
for i in xrange(2, fin+1):
if candidates[i]:
candidates[2*i::i] = [None] * (n//i - 1)
# Filter out non-primes and return the list.
return [i for i in candidates[2:] if i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment