89 lines
2.8 KiB
Plaintext
89 lines
2.8 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "f118733f",
|
|
"metadata": {},
|
|
"source": [
|
|
"# [Circular Primes](https://projecteuler.net/problem=35)\n",
|
|
"\n",
|
|
"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",
|
|
"\n",
|
|
"## Relevant sequences\n",
|
|
"* Circular primes: [A068652](https://oeis.org/A068652)\n",
|
|
"\n",
|
|
"#### Copyright (C) 2025 filifa\n",
|
|
"\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)."
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "SageMath 9.5",
|
|
"language": "sage",
|
|
"name": "sagemath"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.11.2"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|