I am building a program to find all primes smaller than a number n using the algorithm of the sieve of Eratosthenes using python. The algorithm first creates a list of numbers from 2 to n, then iterates over the list removing the first element available and the corresponding multiples. The problem is that I don't seem to get the right result doing this way. I would also appreciate any suggestion to improve the performance.
This is the algorithm:
def primes(max):
'''The sieve of Eratosthenes
Algorithm to find all primes smaller than max'''
init = time.clock()
allNum = [a for a in range(2, max+1)]
primes = []
for n in allNum:
# remove all multiples of prime n
toRemove = (a for a in range(n, max+1, n) if a in allNum)
for i in toRemove:
print('toRemove:', i)
allNum.remove(i)
# add the prime to the list
primes.append(n)
deltaT = time.clock() - init
print('Time taken to process:', deltaT)
return primes
(SOLVED) This is how I changed it:
while len(allNum) != 0:
prime = allNum[0]
# remove all multiples of prime
toRemove = (a for a in range(prime, max+1, prime) if a in allNum)
for i in toRemove:
print('toRemove:', i)
allNum.remove(i)
# add the prime to the list
primes.append(prime)