"There's only $1! + 2! + 3! + \\cdots + 9! = 409113$ $n$-digit pandigital numbers. This is a small enough number to brute force, but we can easily optimize even further by applying a [divisibility rule](https://en.wikipedia.org/wiki/Divisibility_rule).\n",
"\n",
"If the digits of a number sum to a multiple of 3, that number is divisible by 3. Since:\n",
"* the digits of every 5-digit pandigital number will sum to 15\n",
"* the digits of every 6-digit pandigital number will sum to 21\n",
"* the digits of every 8-digit pandigital number will sum to 36\n",
"* the digits of every 9-digit pandigital number will sum to 45\n",
"\n",
"all of these numbers will be divisible by 3, and therefore not be prime. Consequently, to find the largest $n$-digit pandigital prime, we only need to check 4-digit and 7-digit pandigital numbers."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "9fead48d",
"metadata": {},
"outputs": [],
"source": [
"from itertools import permutations\n",
"\n",
"pandigitals = set()\n",
"for n in (4, 7):\n",
" for permutation in permutations(range(1, n + 1)):\n",
" k = sum(10^i * d for (i, d) in enumerate(reversed(permutation)))\n",
" pandigitals.add(k)"
]
},
{
"cell_type": "markdown",
"id": "5a4dd5de",
"metadata": {},
"source": [
"Now just sort largest-to-smallest and find the first prime."
"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)."