online advertising

Monday, August 19, 2013

Problem 4: Largest palindrome product

Problem: 

Please find the problem here.

Solution:

The problem size is just too small - consider the set of all pairs or 3 digits numbers = $ (999-100+1)^2 = 810000 $, any computer is going to find the answer very quickly. Here is the code:


namespace Euler
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal static partial class Program
    {
        public static void Problem004()
        {
            int max = 0;
            for (int i = 999; i >= 100; i--)
            {
                for (int j = 999; j >= 100; j--)
                {
                    int candidate = i * j;
                    if (candidate == Reverse(candidate)) 
                    {
                        if (candidate > max)
                        {
                            max = candidate;
                        }
                    }
                }
            }
            Console.WriteLine(max);
        }

        private static int Reverse(int i)
        {
            int j = 0;
            while (i > 0)
            {
                j = j * 10 + i % 10;
                i = i / 10;
            }
            return j;
        }
    }
}

At this point - don't you think Project Euler problem is really simple? All just brute force, isn't it. NO! Problems are getting harder and harder, you will see them soon.

Answer: 906609

No comments :

Post a Comment