There is certainly a more efficient algorithm solve Euler #4, but here is my solution. Runtime averages around 500ms.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Diagnostics; namespace Euler4 { class Program { static void Main(string[] args) { long maxPal = 0; long iMax = 0; long jMax = 0; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 100; i <= 999; i++) { for (int j = 100; j <= 999; j++) { long curPal = (long)(i * j); if (CheckPallindrome(curPal)) { if (curPal > maxPal) { maxPal = curPal; iMax = i; jMax = j; } } } } sw.Stop(); Console.WriteLine("Runtime was " + sw.ElapsedMilliseconds + " ms"); Console.WriteLine("Runtime was " + sw.ElapsedTicks + " ticks "); Console.WriteLine(iMax + " x " + jMax + " = " + maxPal); Console.ReadLine(); } private static bool CheckPallindrome(long input) { PallindromeChecker pc = new PallindromeChecker(); pc.Pal = input; return pc.IsPallindrome(); } } class PallindromeChecker { private long _pal; private string forward, reverse; public long Pal { get { return _pal; } set { _pal = value; } } public bool IsPallindrome() { GetReversedLong(); if (forward == reverse) return true; return false; } private void GetReversedLong() { forward = Convert.ToString(_pal); StringBuilder temp2 = new StringBuilder(); char[] arr = new char[forward.Length - 1]; arr = forward.ToCharArray(); for (int i = forward.Length - 1; i >= 0; i--) { temp2.Append(arr[i]); } reverse = temp2.ToString(); } } }
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.