Lazy List Generator Problem

Gerald Britton gerald.britton at
Fri Jan 16 20:50:48 CET 2009

For those interested in the Sieve of Eratosthenes, have a look at:

The examples in the paper are in Haskell, but I have been
corresponding with the author who provided this Python version:

def sieve():
    innersieve = sieve()
    prevsquare = 1
    table  = {}
    i = 2
    while True:
        if (table.has_key(i)):
            prime = table[i]
            next = i+prime
            while next in table:
                 next = next + prime
            table[next] = prime
            yield i
            if i > prevsquare:
                j =
                prevsquare = j * j
                table[prevsquare] = j
        i = i + 1

Only of 65056 bytes (less than 1/16 MB) of heap is used when
calculating the millionth prime.  It is also very fast but can be even
further optimized using a wheel as described in the paper.  FWIW I was
so intrigued I went off to learn Haskell just so I could follow the
paper properly.

More information about the Python-list mailing list