Find the largest palindrome made from the product of two 3-digit numbers

This “obvious” solution to this problem didn’t force me to use any new techniques, but at least it got me to familiarize myself with F# array and string methods.

module Problem4 =
//we have to write (fun n -> System.String n) instead of just System.String because class constructors can't be used without arguments :-(
let isPalindrome n = n.ToString() |> Array.ofSeq |> Array.rev |> (fun n -> System.String n) |> System.Convert.ToInt32 = n
let min = 100
let max = 999
//ridiculously inefficient way of generating all pairs
let brutePairs = seq{for i in min .. max do
for j in min .. max do
yield i * j}
let ans = brutePairs |> Seq.filter isPalindrome |> Seq.max

I put obvious in quotes above, because Dustin Campbell had an even more obvious solution for reversing a number that didn’t occur to me. The use of strings to manipulate numbers is a sure sign that I spent too much time using Ruby at Centaur :-).

let reverse n =
let rec loop x acc =
if x = 0 then acc
else loop (x/10) (acc*10 + (x%10))
loop n 0
let isPalindrome n =
n = reverse n

### Like this:

Like Loading...

*Related*