// you’re reading...

Project Euler Solutions

Project Euler Problem 32 Solution

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading ... Loading ...

Problem Description

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, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.

Analysis

This is a perfect application for a simple brute force program that iterates through the possibilities and produces a solution. The only thought of optimization was to only generate as many 4 digit products as necessary in order to keep the concatenation of i, j and p at the required 9 digits. The only combinations are a 1 digit number times a 4 digit number (lowest valid = 1234) or a 2 digit number times a 3 digit number (lowest valid = 123).

A set is used to ignore duplicate products.

Solution

Runs < 1 second in Python.

from Euler import is_pandigital
 
p = set()
for i in range(2,100):
  start = 1234
  if i>9: start = 123
  for j in range(start, 10000/i+1):
    if is_pandigital(str(i)+str(j)+str(i*j)): p.add(i*j)
 
print "Answer to PE32 = ",sum(p)

Comments

  • More information on the Euler module can be found on the tools page.
  • This solution took 21,220 iterations.
  • Of the 9 sets found, the last one was 48 × 159 = 7632

Discussion

2 comments for “Project Euler Problem 32 Solution”

  1. Did you submit this answer? It seems to me that it’s not right. Don’t you need to consider cases like 4*3=12? And at the end don’t you have to check if there are repeated products? I’ve spent over an hour on this problem and I can’t get the right answer… Thanks!

    Posted by Ilan | August 20, 2009, 7:41 pm
    • The ‘set’ data type in Python takes care of repeated products so the solution is simply adding the set. I ran the app again and it produces a correct answer.

      Please understand that the problem is looking for a 1-9 pandigital sequence so all digits 1-9 must be used once. 4*3=12 leaves out 5,6,7,8 and 9.

      Posted by Mike | August 24, 2009, 6:41 pm

Post a comment