Sunday, April 17, 2011

Project Euler - Problem 4

Welcome to week 4 of my Project Euler series.

Problem 4:
Find the largest palindrome made from the product of two 3-digit numbers.

Details:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Code:
// Find the largest palindrome made from the product of two 3-digit numbers.
class Problem4
{
    static void Main(string[] args)
    {
        int product;
        int answer = 0;
        string productString;

        for (int i = 999; i > 99; i--)
        {
            for (int j = 999; j > 99; j--)
            {
                product = i * j;
                productString= product.ToString();
                if (productString == ReverseString(productString))
                {
                    if (product > answer)
                    {
                        answer = product;
                    }
                }
            }
        }
        Console.WriteLine(answer);
        Console.Read();
    }

    private static string ReverseString(string input)
    {
        var inputArray = input.ToCharArray();
        var reversedValue = string.Empty;

        for (int i = input.Length-1; i >= 0; i--)
        {
            reversedValue += inputArray[i];
        }

        return reversedValue;
    }
}


Solution:
I am not sure why, but this one caused me a little too much grief.  I was thinking entirely too hard about it. Once I decided to simplify it to ridiculous proportions, then it worked.  I have three variables.  The first is for the product of the current three digit numbers, the second is the current highest product, and the third is the current product as a string.  The main loop of this program is a for inside a for, so that we can go through the list from 100 to 999 twice, since it is the sum of two three digit numbers. The following steps go pretty fast. I take the product, check if it is the same reversed, then see if it is larger than the reigning champ.  If so swap it out, then move on to the next.  The final steps as always are print and finish.

The reversal of the number is also very easy. I simply turn it into an array of characters, then loop through it backwards, placing them at the first empty space that is found.  A quick save and return, and all is well in the world.

This problem really moved along first when I stopped thinking about it too much. I could hear every programming instructor or professor that I have ever had yelling "KISS - Keep It Simple Stupid" over and over.  Perhaps they didn't yell it, but it got drilled into us all in either case.  And it really is true as I found out first hand.

Until next time...

Enjoy!

0 comments:

Post a Comment