Pandigital Prime¶
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.
If the digits of a number sum to a multiple of 3, that number is divisible by 3. Since:
- the digits of every 5-digit pandigital number will sum to 15
- the digits of every 6-digit pandigital number will sum to 21
- the digits of every 8-digit pandigital number will sum to 36
- the digits of every 9-digit pandigital number will sum to 45
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.
In [1]:
from itertools import permutations
pandigitals = set()
for n in (4, 7):
for permutation in permutations(range(1, n + 1)):
k = sum(10^i * d for (i, d) in enumerate(reversed(permutation)))
pandigitals.add(k)
Now just sort largest-to-smallest and find the first prime.
In [2]:
for p in reversed(sorted(pandigitals)):
if is_prime(p):
break
p
Out[2]:
7652413
Relevant sequences¶
Copyright (C) 2025 filifa¶
This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license and the BSD Zero Clause license.