Skip to content

Instantly share code, notes, and snippets.

@kgaughan
Created December 27, 2008 09:13
Show Gist options
  • Save kgaughan/40227 to your computer and use it in GitHub Desktop.
Save kgaughan/40227 to your computer and use it in GitHub Desktop.
from itertools import count
def sieve():
"""
The Sieve of Erastosthenes.
If you wanted to speed this up, your best bets are to throw in a wheel.
The heapq module's already written in C, so that's as fast as it's going
to get, though if you can think of a way to avoid quite so many calls to
heapq.heapreplace() (or prevent if from sifting the heap prematurely for
us), that'd help.
"""
yield 2
q = [(4, 2)]
for i in count(3):
composite, prime = q[0]
if composite == i:
while composite == i:
heapq.heapreplace(q, (composite + prime, prime))
composite, prime = q[0]
else:
heapq.heappush(q, (i * i, i))
yield i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment