"SageMath's implementation of $\\phi(n)$ is fast enough that you could brute force this if you wanted, but if we're clever, we can solve more quickly.\n",
"\n",
"We'll write a simple function for determining if two numbers are digit permutations of each other."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "e6757165",
"metadata": {},
"outputs": [],
"source": [
"def is_permutation_pair(a, b):\n",
" s, t = str(a), str(b)\n",
" return sorted(s) == sorted(t)"
]
},
{
"cell_type": "markdown",
"id": "bdeb8c77",
"metadata": {},
"source": [
"As in [problem 69](https://projecteuler.net/problem=69),\n",
"We can calculate the totients of the numbers up to $10^7$ using a very similar approach to the [sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) for generating prime numbers (see [problem 10](https://projecteuler.net/problem=10)). Iterating over values of $n$, if `totients[n] == n - 1`, then $n$ is prime, and we'll update all its multiples using the above formula."
"$n-1$ can't be a permutation of $n$, so our solution won't be prime. If $n$ is composite, then we'll check if $n/\\phi(n)$ is small and if $\\phi(n)$ is a permutation of $n$, keeping track of the best answer so far."
"Note: lots of people in the problem thread make the assumption that the answer must be a [semiprime](https://en.wikipedia.org/wiki/Semiprime). However, Steendor points out that for certain upper bounds, this assumption does not hold. For instance, $2817 = 3^2 \\times 313$ and $\\phi(2817) = 1872$, and 2817/1872 is the lowest ratio until 2991. 2817 may be an exception rather than the norm (all the other numbers in A102018 up to $10^8$ are semiprimes); nevertheless, this solution avoids making the assumption.\n",
"\n",
"## Relevant sequences\n",
"* All numbers $n$ such that $\\phi(n)$ is a digit permutation: [A115921](https://oeis.org/A115921)\n",
"* Subsequence of A115921 such that $n/\\phi(n)$ is a record low: [A102018](https://oeis.org/A102018)\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)."