Posted By

rtperson on 06/01/11


Tagged

math algorithm puzzle


Versions (?)

Euler Problem 4 in Haskell


 / Published in: Haskell
 

URL: http://projecteuler.net/index.php?section=problems&id=4

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.

There are shorter ways to do this, and I cheat a bit by counting down to 900 rather than 100, but this one short-circuits when it finds the answer, and so is very efficient.

  1. isPalindrome :: String -> Bool
  2. isPalindrome [] = True
  3. isPalindrome str = let str2 = reverse str
  4. in (str2 == str)
  5.  
  6. factors :: [(Int, Int)]
  7. factors = [(x,y) | x <- reverse [900..999], y <- reverse [900..999]]
  8.  
  9. findPal :: [(Int, Int)] -> Int
  10. findPal [] = 0
  11. findPal ((x,y):xs) = let pal = isPalindrome $ show mult
  12. mult = x * y
  13. in case pal of
  14. True -> mult
  15. False -> findPal xs
  16.  
  17. main = do
  18. return (findPal factors)

Report this snippet  

You need to login to post a comment.