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?
Fisrt of all, $ n \le 9 $.
from itertools import permutations
from functools import reduce
from math import sqrt
def get_digits(last):
return [6, 5, 4, 3, 2] if last == 1 else [6, 5, 4, 2, 1]
def combine_digits(digits):
return reduce(lambda n, d: n*10+d, digits, 0)
combine_digits([1,2, 3])
def is_prime(n):
# n is already not even
assert n % 2 != 0
return all((n % i for i in range(3, int(sqrt(n))+1, 2)))
is_prime(11)
is_prime(49)
def solve():
highest = 7
for last in [3, 1]:
for p in permutations(get_digits(last)):
n = combine_digits((highest, ) + p + (last, ))
if is_prime(n):
return n
solve()