Guest User

Untitled

a guest
May 25th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. (* Largest palindrome number which is the product of two 3-digit numbers *)
  2. (* Upper bound: 999 x 999 = 998001 *)
  3. (* Largest palindrome: 997799 *)
  4.  
  5. fun pop (x::[]) = (x, [])
  6. | pop (x::xs) = let val (y, ys) = pop xs in (y, x::ys) end
  7. | pop [] = raise Empty;
  8.  
  9. fun palindrome [] = true
  10. | palindrome (x::[]) = true
  11. | palindrome (x::xs) =
  12. let val (y, ys) = pop xs in
  13. x = y andalso palindrome ys
  14. end
  15.  
  16. fun itol n = if n < 10 then [n] else (n mod 10) :: itol (n div 10);
  17.  
  18. fun find_factors _ 999 = NONE
  19. | find_factors n j =
  20. if n mod j = 0 andalso n div j < 999
  21. then SOME (j, n div j)
  22. else find_factors n (j + 1)
  23.  
  24. fun find_pal n = if palindrome (itol n) then
  25. let val factors = find_factors n 100 in
  26. (case factors of
  27. NONE => find_pal (n - 1) (* palindrome, but insufficient *)
  28. | SOME (x, y) => (x, y, n)) (* bingo! *)
  29. end else find_pal (n - 1); (* not palindrome *)
Add Comment
Please, Sign In to add comment