Yet Another Project Euler Series (YAPES) continues with problem four:
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 most straightforward way to determine if a number is palindromic is to convert it to a string and compare that string with its reverse. Sound easy? It is!
One minor snag is the lack of a library function in F# for reversing strings, but that's easily defined like so:
module String =
let rev (s : string) = new string(s.ToCharArray() |> Array.rev)
With String.rev in place, writing an isPalindrome function is trivial.
let isPalindrome n =
let text = Int32.to_string n
text = String.rev text
Using a list comprehension, we can generate all of the palindromes that are products of 3-digit numbers. Once we have this list, producing the result is as simple as passing it to the toLargest function that we defined for Problem Three.
[ for x in 100..999
for y in 100..999
when isPalindrome (x*y) -> x*y ] |> toLargest
Short and sweet—my favorite!