Sieve of Eratosthenes

529 days ago by mpaul

You can generate the prime numbers by starting with an array [0 .. n] and then eliminating numbers that are not prime.

For example, let n = 100:

n = 100 primes = [0..n] primes 
       

Prime numbers are atomic factors.  They terminate a factoring process.

Therefore, 1 is not prime.

primes[1] = 0 primes 
       

2 is prime.  Therefore, any multiple of 2 is not prime.

The first multiple of 2 beyond 2 itself is 2^2 = 4.

We'll start there and set each multiple of 2 to 0:

p = 2 for i in [p^2..n, step = p]: primes[i] = 0 primes 
       

The next prime is 3.  

We will start at 3^2 and set each multiple of 3 to 0:

p = 3 for i in [p^2..n, step = p]: primes[i] = 0 primes 
       

The next prime is 5.

Similarly, we will start at 5^2 and set each multiple of 5 to 0:

p = 5 for i in [p^2..n, step = p]: primes[i] = 0 primes 
       

The next prime is 7.

You know the story.

p = 7 for i in [p^2..n, step = p]: primes[i] = 0 primes 
       

The next prime is 11.

Its next multiple is 121, and that is beyond our original value of n.

Therefore, the numbers remaining in our list are either 0 or prime.

Let's get rid of the 0s:

while 0 in primes: primes.remove(0) primes 
       
 
       

We can summarize what we did for n = 100 and create a function that will work for any value of n:

def sieve(n): primes = [0..n] primes[1]=0 for p in [2..sqrt(n)]: if primes[p]>0: for i in [p^2 .. n, step = p]: primes[i] = 0 while 0 in primes: primes.remove(0) return primes 
       
sieve(100) 
       
sieve(1000) 
       
sieve(10000) 
       

Our sieve function seems to work.  However, for values of n = 100,000 or above, the function takes awhile.

Sage itself contains an efficient way to generate a list of primes:

prime_range(100000)