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?
Here's my implementation in Python 3. Awaiting feedback.
from time import time
def is_prime(number):
"""returns True for a prime number, False otherwise."""
factor = 2
while factor * factor <= number:
if number % factor == 0:
return False
factor += 1
return True
def circulate(number):
"""returns all circulations of a number."""
for n in str(number):
if not int(n) % 2:
return False
circulations = []
digits = list(str(number))
for i in range(len(str(number))):
last = digits.pop()
circulations.append(last + ''.join(digits))
digits = [last] + digits
return [int(x) for x in circulations]
def circular_primes(limit):
"""returns all circular primes below limit."""
all_circulations = [2]
for num in range(3, limit, 2):
if is_prime(num):
check = 0
if circulate(num):
circulations = circulate(num)
for circulation in circulations:
if not is_prime(circulation):
check += 1
if not check:
all_circulations.extend(circulations)
return all_circulations
if __name__ == '__main__':
start_time = time()
print(len(set(circular_primes(200000))))
print(f'Time: {time() - start_time} seconds.')