Skip to content

Instantly share code, notes, and snippets.

@onemouth
Created September 1, 2013 16:36
Show Gist options
  • Save onemouth/6405584 to your computer and use it in GitHub Desktop.
Save onemouth/6405584 to your computer and use it in GitHub Desktop.
sieve.py
from itertools import ifilter
from itertools import islice
def sieve_worker(numbers, table):
head = next(numbers)
if head not in table:
yield head
table[head+head] = [head]
else:
primes = table[head]
del table[head]
for prime in primes:
next_filter = head+prime
if next_filter in table:
table[next_filter].append(prime)
else:
table[next_filter] = [prime]
for prime in sieve_worker(numbers, table):
yield prime
def sieve(numbers):
for prime in sieve_worker(numbers, {}):
yield prime
for i in islice(sieve(itertools.count(2)), 50):
print i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment