Search code examples
pythonpython-2.7sieve-of-eratosthenes

Trying to write an Eratosthenes Sieve in Python. Is this correct and how can I make it faster?


Possible Duplicate:
Fastest way to list all primes below N in python

I have not been doing programming for very long, and I'm just doing this for fun, and I don't know much advanced Python, but... I wrote this, and I wanted to know whether it is actually an Eratosthenes Sieve program, and if it is, how could I make it faster. I don't really want someone to post a program that is a solution, but more tell me how I could adapt mine.

def eratSieve(n):
    all = []
    for a in range(2, n+1):
        all.append(a)               
    for b in all:                       
        for i in range(2,int(round(len(all)/b))):
            while i*b in all:
                all.remove(i*b)
                i+=1
    return all

Thanks for your help.

BTW - It's in Python 2.7


Solution

  • It does not work right.

    The main problem is that you loop on all the value in all and in the while you remove some element from all.

    This way some value in all are not considered, so the function does not remove all the non-prime numbers

    Try to execute it for n=100 and the result you get is

    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99

    while it should be

    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 (from http://en.wikipedia.org/wiki/Prime_number)

    Also, the range of the second for is wrong, since you consider the lenght of the list, not the current value of b and so you check for multiple of 2 only in the first 50 values, the multiple of 3 in the first 17, 5 in the first 9 and so on. From b = 13 you never enter in the inner for, since int(round(len(all)/b)) = 1 and so you have something like for i in range(2,1)