Skip to content

Instantly share code, notes, and snippets.

@julius-datajunkie
Created October 25, 2013 16:59
Show Gist options
  • Save julius-datajunkie/7158041 to your computer and use it in GitHub Desktop.
Save julius-datajunkie/7158041 to your computer and use it in GitHub Desktop.
This generator generates an infinite sequence of primes, one at a time
# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
def PrimesGenerator():
"""
Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment