Project Euler problem 43

February 28th, 2009 at 11:15 am

Problem 43 is the 51st Project Euler problem I’ve solved. To do it, I’ve used a couple of tricks that reduced the runtime considerably from a full brute-force.

A full brute-force for such a problem would be going over all 10-digit numbers, detecting pandigital ones and checking the requested property. Since there are 10 billion 10-digit numbers, this would take a long time.

Here are some ideas of how to reduce the run-time:

First of all, there are only 3,628,800 (10!) 0 to 9 pandigital numbers, so there’s no need to examine all 10 billion 10-digit numbers.

Second, the special property we’re looking for in the numbers can help us considerably reduce the amount of candidates to test.

What I did is consider only numbers whose last 3 digits divide by 17. There are only 58 such numbers (1 to 58, as 17 * 59 > 1000). For each, we should only check the permutations of the 7 remaining digits. Since there are 5040 permutations of 7 digits, we have to check only 58 * 5040 = 292320 candidates for the property.

This, of course, can be reduced further by considering the division by 13 as well, and so on, so I’m sure the problem can even be solved using a pen, some paper and a calculator in not too much time.

Related posts:

  1. Project Euler problem 104
  2. Project Euler problem 12
  3. Project Euler problem 69
  4. Project Euler problem 26
  5. Euler 68 – solving problems the hard way, but having fun along the way

3 Responses to “Project Euler problem 43”

  1. ripper234No Gravatar Says:

    Brute force, 0.72 seconds :)

    (By brute-force I mean going through all permutations and checking them, not going through all 10 digits numbers!)

  2. Gary CapellNo Gravatar Says:

    You can propagate constraints. Once you’ve picked a digit which satisfies the ‘divides by 5′ rule, you’ve reduced your search space for the ‘divides by 7 rule’, and so on. You then bubble down through a list of filters, assigning digits to positions as you go. It takes 1.8ms on my box, making 380 x % y == 0 comparisons.

    FILTERS = [
    	# position, pattern, divisor
    	(6, [x], 5),
    	( (5,7), [x,6,x], 7),
    	(8, [6,7,x], 11),
    	(9, [7,8,x], 13),
    	(10, [8,9,x], 17),
    	(4, [x], 2),
    	(3, [x, 4, 5], 3),
    ]
  3. Gustaf EriksonNo Gravatar Says:

    28s with Perl brute force

Leave a Reply

To post code with preserved formatting, enclose it in `backticks` (even multiple lines)