Problem Thirty Two

14 Dec

Here’s problem thirty two:

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

This is simply a case of looping and creating a function that tests if a given input is pandigital. Again, the upper bounds on the for loops were a bit tricky. I set the limit at 10,000 since the total number of digits cannot exceed 9, so the maximum situation that can occur is 9999 * 1 = 9999 (9 digits).

Here’s the code:

def isPandigital19(s):
	return '0' not in s and len(s) == 9 == len(set(s))

result = set()

for n in range(2, 10000):
	for m in range(2, 10000):
		if n * m > 10000: continue
		elif isPandigital19(str(n)+str(m)+str(n*m)):
			result.add(n*m)

print(sum(result))

So the result is stored in a set, since there could be duplicate multiplicand/multiplier/product pandigitals. We iterate through the possibilities using two for loops, and quickly check if the product is greater than 10,000 to skip to the next iteration. This is because if the product is over 10,000, the total digits of it and its factors are guaranteed to be over 9 digits. Only then do we check if the identity is pandigital using the function isPandigital19().

This function essentially checks the to see if the length of the string (of the identity) is 9 (9 digits), and if there are no duplicates by also testing the set of the string. However, 0 cannot be a digit in the identity since we’re only concerned with the digits 1-9, so that test is also included in the function. The function returns a true or false value, and the rest is self-explanatory.

Answer: 45228

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: