"We're only looking for [circular primes](https://en.wikipedia.org/wiki/Circular_prime) 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.\n",
"\n",
"We can then use Python's [`deque` class](https://docs.python.org/3/library/collections.html) to write a function that cycles through a prime number's digits to check if it is a circular prime."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "9d4833c5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"55\n"
]
}
],
"source": [
"from collections import deque\n",
"\n",
"def is_circular_prime(p):\n",
" d = deque(str(p))\n",
" while True:\n",
" d.rotate()\n",
" rp = int(\"\".join(d))\n",
" if rp == p:\n",
" break\n",
" elif not is_prime(rp):\n",
" return False\n",
" \n",
" return True\n",
"\n",
"\n",
"circular_primes = set(p for p in prime_range(1000000) if is_circular_prime(p))\n",
"print(len(circular_primes))"
]
},
{
"cell_type": "markdown",
"id": "5e21d050",
"metadata": {},
"source": [
"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?\n",
"\n",
"Another note - there aren't that many known circular primes, and all of the known ones greater than one million are [repunits](https://en.wikipedia.org/wiki/Repunit).\n",
"This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)."