We shall say that an \(n\)-digit number is pandigital if it makes use of all the digits \(1\) to \(n\) exactly once. For example, \(2143\) is a \(4\)-digit pandigital and is also prime.
What is the largest \(n\)-digit pandigital prime that exists?
For any \(k\), \(10^k \equiv 1 \mod 3\), because \(10^k - 1\) consists entirely of \(9\)'s. If we represent the digits of an \(n\)-digit number \(m\) as \(m_{n-1} m_{n-2} \ldots m_0\), then
\[ m = \sum_{k=0}^{n-1} 10^k m_k \equiv \left( \sum_{k=0}^{n-1} m_k \right) \mod 3. \]Therefore, a number is divisible by \(3\) if and only if its digital sum is divisible by \(3\).
The digital sum of an \(8\)-digit pandigital number is \(36\). The digital sum of a \(9\)-digit pandigital number is \(45\). Both of these are divisible by \(3\), so pandigital primes can have at most \(7\) digits. From this conclusion, it's simple to check numbers from \(7654321\) downwards until we hit one that's both pandigital and prime. This happens pretty quickly: the answer ends up being \(7652413\).
from sympy import isprime
def p41():
for m in range(7654321, 7123455, -1):
if ''.join(sorted(str(m))) == "1234567" and isprime(m):
return m