Created
September 1, 2013 16:36
-
-
Save onemouth/6405584 to your computer and use it in GitHub Desktop.
sieve.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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