Skip to content

Instantly share code, notes, and snippets.

@scogle
Created May 17, 2015 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scogle/596591782f7db49e560b to your computer and use it in GitHub Desktop.
Save scogle/596591782f7db49e560b to your computer and use it in GitHub Desktop.
def sieve(limit):
# Start by generating a list of bools with all even indexes flagged as not prime
# This substitutes the index in a list for actual numbers with a boolean
# flag indicating primality instead of actually maintaining the int in memory
# (since bools are much cheaper)
start = [False if i % 2 == 0 else True for i in range(limit)]
# Make sure to set 0 and 1 as not prime
start[0] = start[1] = False
for (i, isprime) in enumerate(start):
# If it's prime, yield it and set its multiples to false, else move on
if isprime:
# this is the magic - the yield keyword turns this into a generator
# meaning that you can start iterating over the results of sieve()
# as they're generated
yield i
# xrange is like range but cheaper
for n in xrange(2*i, limit, i): # Mark factors non-prime
start[n] = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment