Search code examples
c#linqpalindrome

Project Euler #4 with C#


i'm trying to solve project euler #4 with c# and according to previous posts, i couldn't find any solution of this problem with c#.

The question is:

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.

Below is my code, but when i look how it flows, i can't see my mistake. How can i fix it?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CS_11_project_Euler_problem_4
{

class Program
{

    static void Main(string[] args)
    {
        int x, y;
        string product="" , res="";

        for (x = 100; x <= 999; x++)
        {
            for (y = 100; y <= 999; y++)
            {
                product = Convert.ToString(x*y);

                if (product == new String(product.Reverse().ToArray()))
                {
                    Console.WriteLine("X=" + x + " Y=" + y );
                    res = product;

                    Console.WriteLine("Polindrome is: " + res);
                }

                else { continue; }
            }
        }
    }
}
}

The result that my code found is 580085, Here is my output's screenshot. It displays every result palindrome number with its multipliers.

enter image description here

Eventough according to projecteuler.net my result is not correct. One of my outputs was giving me the actual result. 906609 . It's the second result before my code's last palindrome. I think i was wrong to think increasing multiliers within nested for loops because it was unintentionally based on "biggest X gives biggest multiplier logic". In order to prevent it i'm going to convert my res and product to integer once more, and always keep the bigger product result in variable product


Solution

  • Because once you do find a palindrome you are looping forever inside your while loop. Change the while to and if and it should work.

    EDIT:

    Yes, you will need to keep track of the largest product found so far, not simply assume the last product found is the largest.