Project Euler 004 – C#

22 02 2011

Problem 4

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.

Solution

using System.Collections.Generic;

 

//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.

 

namespace ProjectEulerCSharp_004

{

    class Program

    {

        static void Main(string[] args)

        {

            //simple placeholder for our

            //biggest palindrome

            int maxPalindrome = 0;

 

            //loop through each 3-digit number

            for (int i = 100; i < 1000; i++)

            {

                //this is a slight optimization

                //over our F# solution because

                // 100 * 101 = 101 * 100 so we

                // don’t need to perform the second

                // multiplication

                for (int j = i; j < 1000; j++)

                {

                    int product = i * j;

                    //used an extension method to test for

                    //palindromicity (is that a word)

                    if (product.IsPalindrome()

                        && product > maxPalindrome)

                    {

                        maxPalindrome = product;

                    }

                }  

            }

            System.Console.WriteLine(maxPalindrome);

        }

    }

 

    // extension methods are awesome

    public static class Extensions

    {

        // here we create a function called

        // IsPalindrome that uses the same

        // technique as the F# function

        public static bool IsPalindrome(this int i)

        {

            // get a convenient list of chars

            List<char> chars =

                new List<char>(i.ToString().ToCharArray());

            // reverse them

            chars.Reverse();

            // are we a palindrome?

            return i == int.Parse(new string(chars.ToArray()));

        }

    }

}

 

Discussion

My favorite part of this solution is the use of the extension method.  Why don’t we use those all the time?  Of course, the generic List structure offers some helpful routines as well.

If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).

Advertisements