def sieve_of_erastothenes(number):
"""Constructs all primes below the number"""
big_list = [2] + range(3, number+1, 2) # ignore even numbers except 2
i = 1 # start at n=3, we've already done the even numbers
while True:
try:
# use the next number that has not been removed already
n = big_list[i]
except IndexError: # if we've reached the end of big_list we're done here
return big_list
# keep only numbers that are smaller than n or not multiples of n
big_list = [m for m in big_list if m<=n or m%n != 0]
i += 1
On my computer, this code takes about half a second to calculate all primes below 10,000, fifteen seconds to do 100,000, and a very long time to calculate primes up to one million. I'm pretty sure it's correct (the first few numbers in the returned sequence are right), so what can I do to optimise it?
I've tried a version that removes the relevant numbers in-place but that takes even longer (since it takes O(n) to move all the remaining numbers down).