C#: Project Euler Solution to Problem 32

http://projecteuler.net/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 x 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.

public static LinkedList<string> onetonine = new LinkedList<string>();
static void Main(string[] args)
{
    LinkedList<int> distinct_product = new LinkedList<int>();
    int product = 0;
    for (int a = 1; a < 2000; a++)
    {
        for (int b = 1; b < 2000; b++)
        {
            product = a * b;
 
            if (isDigits(a + "" + b + "" + product))
            {
                if (!distinct_product.Contains(product) )
                    distinct_product.AddLast(product);
            }
        }
    }
    int sum = 0;
    foreach (int prod in distinct_product)
        sum += prod;
    Console.WriteLine("sum : "+sum);
}
 
public static bool isDigits(string s)
{
    onetonine.Clear();
    onetonine.AddLast("1");
    onetonine.AddLast("2");
    onetonine.AddLast("3");
    onetonine.AddLast("4");
    onetonine.AddLast("5");
    onetonine.AddLast("6");
    onetonine.AddLast("7");
    onetonine.AddLast("8");
    onetonine.AddLast("9");
    if (s.Length != 9)
        return false;
    for (int i = 0; i < s.Length; i++)
    {
        if (onetonine.Contains("" + s[i]))
            onetonine.Remove("" + s[i]);
        else
            return false;
    }
    return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *