kgaughan (owner)

Revisions

gist: 40227 Download_button fork
public
Public Clone URL: git://gist.github.com/40227.git
Embed All Files: show embed
erastosthenes.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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