Eratosthenes' Sieve

Find all primes up to a given $n$

James Blood 2017

Here is a version of the famous and ancient algorithm, Eratosthenes' sieve. It starts with a full set of numbers from 2 to $n$ before eliminating the multiples. This leads inexorably to a set populated solely with the prime numbers. Full details are available on Wikipedia.

This works well enough up to $10^7$. Orders of magnitude higher than that begin to be very slow and one should think about separating the set into various $\Delta$s (see the wiki). I may add this functionality soon.


In [ ]:
def sieve(n):
    "Simple version of the Eratosthenes' sieve algorithm"
    #initialise a list of Booleans with 0,1 set to false (2 is the first prime)
    primes=[False] * 2 + [True] * (n-1)
    for i,isprime in enumerate(primes): #number the entries in the list
        if isprime: #if it's == True
            yield i 
            for x in range(i**2,n+1,i): #work through the list i**2 is the more arithemetically efficient start point
                primes[x]=False