Friday 10 April 2009

PROJECT EULER #4

Link to Project Euler 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.

Int to string to char[], reverse, back to string etc. is another recurring pattern in these problems.


using System;
using System.Collections.Generic;

namespace ProjectEuler
{
class Program
{
static void Main(string[] args)
{
//Problem 4
DateTime start = DateTime.Now;
List<int> palindromes = new List<int>();
for(int i = 999;i>99;i--)
{
for(int j = 999;j>99;j--)
{
string p = (i*j).ToString();
char[] q = p.ToCharArray();
Array.Reverse(q);
string r = new string(q);
if(p.Equals(r))
palindromes.Add(i*j);
}
}
palindromes.Sort();
TimeSpan time = DateTime.Now-start;
Console.WriteLine("{0}\nThis took {1}",palindromes[palindromes.Count-1] ,time);
Console.ReadKey();
}
}
}

No comments: