Circular Primes¶
We're only looking for circular primes below one million, which makes this search not too strenuous. Obviously, being prime is a precondition for being a circular prime, so we can start our search by only checking primes below one million.
We can then use Python's deque class to write a function that cycles through a prime number's digits to check if it is a circular prime.
from collections import deque
def is_circular_prime(p):
d = deque(str(p))
while True:
d.rotate()
rp = int("".join(d))
if rp == p:
break
elif not is_prime(rp):
return False
return True
circular_primes = set(p for p in prime_range(1000000) if is_circular_prime(p))
print(len(circular_primes))
55
There are other optimizations you can make - for instance, every multi-digit circular prime can only be composed of the digits 1, 3, 7, and 9 (since having another digit would eventually result in a rotation that ends in an even number or 5, which obviously isn't prime) - but why bother (for this problem) when it's already this fast?
Another note - there aren't that many known circular primes, and all of the known ones greater than one million are repunits.
Relevant sequences¶
- Circular primes: A068652
Copyright (C) 2025 filifa¶
This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license and the BSD Zero Clause license.