For exercise, I wrote this code:
def BigPrime(numP, plist = [], x = 1, counter =0):
while len(plist) <= numP:
if x == 1 or x == 2 or x == 5:
plist.append(x)
elif x % 2 is not 0 and int(str(x)[-1]) is not 5:
for div in plist[1:]:
if x % div == 0:
break
else:
plist.append(x)
counter += 1
x += 1
return plist, counter
It is a simple algorithm that should return a list of the first n primes. When I tried to optimize it, I wanted to cut down all the possible already know not primes from the range. That brought me to:
int(str(x)[-1]) is not 5
But then when I timed it, I saw that the code ran slower. Why? It worked, and the for
iterations were less indeed, but yet it was slower.
Also, when it comes to optimization, I'm a black hole of ignorance. Any further way I could improve it?
plist
forces you to write the loop asfor div in plist[1:]:
whereas if you left it out you could writefor div in plist:
and avoid the copy. \$\endgroup\$is not 0
, use!= 0
;is
tests identity, and you want to test equality. It's only an implementation detail that it works at all. \$\endgroup\$