Pandigital prime (Euler Problem 41)

Back to overview.

[https://projecteuler.net/problem=41]

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?

In [49]:
def expmod(base, exp, m):
    if exp == 0:
        return 1
    if (exp % 2 == 0):
        return (expmod(base, exp // 2, m) ** 2 % m)
    return (base * expmod(base, exp - 1, m) % m)
    
def expmod_naiv(base, exp, m):
    return base ** exp % m

def fermat_test(n):
    a = n - 3
    return expmod(a, n, n) == a
In [50]:
assert(expmod(2, 100000, 2143) == expmod_naiv(2, 100000, 2143))
In [51]:
assert(fermat_test(2143))
In [54]:
import itertools

for pandigital in itertools.permutations("7654321"):
    p = int("".join(pandigital))
    if fermat_test(p):
        s = p
        break
        
print(s)
assert(s == 7652413)
7652413