Euler Problem 32

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.
I’m surprise I got this one so easily. Mind you I had to think of a few ways to simplify. One was to realize that if I iterated up to 4000, the resulting product would easily exceed 7 digits, which is the largest possible product size.
Next I had to find an efficient way to confirm if only one digit was used. String.split might have worked, but what if the digit is at the beginning or end? I settled on String.replace, and tested for a reduction in length of only one. Works fast. The answer pops out the end in only 11 seconds.
import java.util.*;

public class Euler32
{
    public static void main(String[] args)
    {
        System.out.print(“Problem 32:\n”);
        Euler32 e = new Euler32();
        System.out.print(“Answer = ” + e.Problem()+ “\n”);
    }
    public String Problem ()
    {
        ArrayList<Integer> p = new ArrayList<Integer>();
        String [] digits = {“1″,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9”};
        String num = “”;
        boolean flag = true;
        int len = 0;
        int sum = 0;
        for (int a = 1; a <= 4000; a++)
        {
            for (int b = 1; b <= 4000; b++)
            {
                num = String.valueOf(a)+String.valueOf(b)+String.valueOf(a*b);
                len = num.length();
                flag = true;
                if (num.contains(“0”) == false && len == 9)
                {
                    for (String d: digits)
                    {
                        if (num.replace(d, “”).length() != len -1)
                            flag = false;
                    }
                    if (flag)
                    {
                        if (p.contains(a*b) == false)
                            p.add(a*b);
                        System.out.format(“%s\n”, num);
                    }
                }
            }
        }
        for (int n: p)
            sum +=n;
        return String.valueOf(sum);
    }
}

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 )

Connecting to %s