patternpythonMinor
Euler 35 - python solution taking too long
Viewed 0 times
longtoopythoneulersolutiontaking
Problem
Here is my solution for Project Euler 35. (Find the number of circular primes below 1,000,000. Circular meaning all rotations of the digits are prime, i.e.
I know there are many solutions out there, I just want to know why this one is soooo slow. I suspect it has something to do with the
197, 719, 971.) The code takes about 30 minutes to run. Can you help me identify which parts of the algorithm are hogging up computation time?I know there are many solutions out there, I just want to know why this one is soooo slow. I suspect it has something to do with the
p.count function call.pis initialized to a list of all primes below 1 million using the Sieve of Eratosthenes.
totalis initialized to 0.
for i in p:
primer = str(i)
circ = 1
for j in range(len(primer)-1):
primer = primer[1:]+primer[:1]
if (p.count(int(primer)) == 1):
circ += 1
if circ == len(primer):
total += 1Solution
Your
p is a list. Then you do p.count(x) to see if x is a prime. This does a linear search of the list, and in fact, has to examine every element of p, not just those up to the occurrence of x. Instead, change p to a set. It will run much faster. Also, once you see that a rotation is not prime, you can stop checking all the rotations.Context
StackExchange Code Review Q#8371, answer score: 7
Revisions (0)
No revisions yet.