I'm doing another Project Euler problem, number 35:
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
import math
num = 0
primeList = []
def isprime(test):
if test == 2:
primeList.append(2)
return True
elif test < 2:
return False
else:
for i in primeList:
if i > math.sqrt(test):
break
elif test % i == 0:
return False
primeList.append(test)
return True
def rotations(n):
answer = []
rotation = n
while not rotation in answer:
answer.append(rotation)
rotation = int(str(rotation)[1:] + str(rotation)[0])
return answer
for i in range(2,1000000):
numList = rotations(i)
valid = True
for j in numList:
if not isprime(j):
valid = False
if valid:
num += 1
print(num)
I need help improving my code speed. What I really think is happening is the rotations()
function is slowing the whole thing down.