Search code examples
c#numberspalindrome

Palindrome number product of two 3-digit numbers - Project Euler Solution 4 - Brute Force not working


I am using this code to solve problem. 4 on Project Euler. The problem reads:

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.

I have tried to solve the problem. My code returns a palindrome number and a fairly big one too. But it is incorrect. I have also found a correct solution at MathBlog.dk. But what is wrong with my code? --

long result = 0;
for (long x = 100; x <= 999; x++)
{
    for (long y = 100; y <= 999; y++)
    {
        long num = x * y;
        if (num.ToString() == StringFunctions.ReverseString(num.ToString()))
        {
                result = num;
        }
    }
}
Console.WriteLine("Result : {0}", result);

The StringFunctions.RevereString function is as follows:

public static class StringFunctions
{
    public static string ReverseString(string s)
    {
        string result = "";
        for (int i = s.Length - 1; i >= 0; i--)
        {
            result += s.Substring(i, 1);
        }
        return result;
    }
}

My code returns 580085 but the correct answer is 906609. I don't want to know about better solutions. I just want to know why my code isn't working.

Any help will be much appreciated. Thanks in advance.


Solution

  • Your result is storing the last palindrome number obtained from the loop but not the largest one.

    Both the variables X and Y iterate from 100 to 999

    Imagine a case when (assuming all obtained numbers are palindromes) x = 500 and y = 500. It will execute earlier than x = 990 and y = 100. But in the earlier case the palindrome is larger but your code stores the smaller one. Use an if condition to get the largest palindrome:

    long result = 0;
    for (long x = 100; x <= 999; x++)
    {
        for (long y = 100; y <= 999; y++)
        {
            long num = x * y;
            if (num.ToString() == StringFunctions.ReverseString(num.ToString()))
            {
                if(result < num)
                {
                result = num;
                }
            }
        }
    }
    Console.WriteLine("Result : {0}", result);