An n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. This is a thing that I first encountered while solving Project Euler problems and it keeps on turning up – most recently (for me) in problem 43.

The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.

Let d_{1} be the 1^{st} digit, d_{2} be the 2^{nd} digit, and so on. In this way, we note the following:

d_{2}d_{3}d_{4}=406 is divisible by 2
d_{3}d_{4}d_{5}=063 is divisible by 3
d_{4}d_{5}d_{6}=635 is divisible by 5
d_{5}d_{6}d_{7}=357 is divisible by 7
d_{6}d_{7}d_{8}=572 is divisible by 11
d_{7}d_{8}d_{9}=728 is divisible by 13
d_{8}d_{9}d_{10}=289 is divisible by 17

Find the sum of all 0 to 9 pandigital numbers with this property.

My eventual approach was (mainly) to brute-force my way through all of the possible pandigitals and testing each against the divisible criteria listed. This, however, raised its own problem: How do I quickly generate a list of all nine digit pandigitals?

The answer turned out to be a rather elegant application of the itertools module.

#!/usr/bin/env python
import itertools
def yield_pandigitals(length):
""" Yields all 0 to length pandigitals
length is an integer between 1 and 9 """
for pandigital in list(itertools.permutations(range(length + 1))):
yield int(''.join(map(str, pandigital)))

Reader of books, watcher of films, player of games.
British father of three, now living in Belgium and making a living from building interfaces.
View all posts by Paul