Project Euler #4 asks:
Find the largest palindrome made from the product of two 3-digit numbers.
The code is as follows:
module Main where
import Data.List (sortBy)
import Data.Ord (comparing)
palindromes :: [Integer]
palindromes = [calcPalindrome a b c | a <- [1..9], b <- [0..9], c <- [0..9]]
where
calcPalindrome a b c = 100001 * a + 10010 * b + 1100 * c
is3Digit :: Integer -> Bool
is3Digit n = n >= 100 && n <= 999
isDiv :: Integer -> Integer -> Bool
isDiv n d = n `mod` d == 0
-- returns all multiples of 2 3-digit numbers
-- for palindromes
isMultiple :: Integer -> Bool
isMultiple n = not $ null threeMultiples
where
multiples :: [(Integer, Integer)]
multiples = do
d <- [10..99]
if n `isDiv` (d * 11)
then return (d * 11, n `div` (d * 11))
else []
threeMultiples :: [(Integer, Integer)]
threeMultiples = filter (\ (m, n) -> is3Digit m && is3Digit n) multiples
problem4 :: Integer -> Integer
problem4 n =
head $ filter isMultiple $ sortBy (flip compare) $ filter (< n) palindromes
main :: IO ()
main = do
_ <- getLine
contents <- getContents
let cases = map read $ lines contents
let results = map problem4 cases
mapM_ print results
I'd appreciate comments on isMultiple
and problem4
as they seem rather messy. Any other general comments are welcome too.