I have a function that lists the prime numbers smaller than N:
def ListPrimes(N):
list = [2]
for n in range(3, N, 2):
for i in range(3, int(sqrt(n)+1)):
if n % i == 0:
break
else:
list.append(n)
return list
I tried to make it faster, so I changed one line to the following:
def ListPrimesFaster(N):
list = [2]
for n in range(3, N, 2):
for i in list:
if n % i == 0:
break
else:
list.append(n)
return list
I was surprised that the second version is at least 5 times slower, given that it is identical to the first except that the variable i has to iterate through a shorter list.
I am trying to find a faster way to list prime numbers smaller than some N.