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.
The easiest way to reverse a number is to convert the number to a string then to a character array and call reserve
F#
let rev (s : string) = new string(s.ToCharArray() |> Array.rev)
C#
n.ToString().ToCharArray().Reverse();
But instead I decided to use the math to reverse the number.
F#
let toLargest l = List.fold1_left max l
let reverse n =
let rec reverseRecursive x res =
if x = 0 then res
else reverseRecursive (x/10) (res*10 + (x%10))
reverseRecursive n 0
let isPalindrome n =
n = reverse n
let largestPalindrome =
[ for i in 100..999
for j in 100..999
when isPalindrome(i*j) -> i*j ] |> toLargest
printf "%i" largestPalindrome
C#
static public class Numbers
{
static private Int64 reverseRecursive(Int64 x, Int64 res)
{
if (x == 0)
return res;
else
return reverseRecursive(x / 10, (res * 10 + (x % 10)));
}
static public Int64 Reverse(Int64 i)
{
return reverseRecursive(i, 0);
}
static public bool isPalindrome(this Int64 i)
{
return i == Reverse(i);
}
}
class Program
{
static void Main(string[] args)
{
Int64 maxPalindrome = Enumerable.Range(100, 900).
SelectMany(i => Enumerable.Range(i, 900 - (i - 100)).Select(j => i * j)).
Where (p => ((Int64) p).isPalindrome()).Max();
Console.WriteLine(maxPalindrome);
Console.ReadLine();
}
}
del.icio.us Tags:
C#,
F#,
Project Euler