Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* Largest palindrome number which is the product of two 3-digit numbers *)
- (* Upper bound: 999 x 999 = 998001 *)
- (* Largest palindrome: 997799 *)
- fun pop (x::[]) = (x, [])
- | pop (x::xs) = let val (y, ys) = pop xs in (y, x::ys) end
- | pop [] = raise Empty;
- fun palindrome [] = true
- | palindrome (x::[]) = true
- | palindrome (x::xs) =
- let val (y, ys) = pop xs in
- x = y andalso palindrome ys
- end
- fun itol n = if n < 10 then [n] else (n mod 10) :: itol (n div 10);
- fun find_factors _ 999 = NONE
- | find_factors n j =
- if n mod j = 0 andalso n div j < 999
- then SOME (j, n div j)
- else find_factors n (j + 1)
- fun find_pal n = if palindrome (itol n) then
- let val factors = find_factors n 100 in
- (case factors of
- NONE => find_pal (n - 1) (* palindrome, but insufficient *)
- | SOME (x, y) => (x, y, n)) (* bingo! *)
- end else find_pal (n - 1); (* not palindrome *)
Add Comment
Please, Sign In to add comment