Skip to content

Instantly share code, notes, and snippets.

@zaneli
Last active December 20, 2015 15:39
Show Gist options
  • Save zaneli/6155811 to your computer and use it in GitHub Desktop.
Save zaneli/6155811 to your computer and use it in GitHub Desktop.
「HaskellでProject Euler(Problem 4~6)」ブログ用
import Data.List
euler4 = maxPalindrome 100 999
maxPalindrome :: (Enum a, Num a, Ord a, Show a) => a -> a -> a
maxPalindrome n m =
let list = sortBy (\x y -> compare y x) [x * y | x <- [n..m], y <- [n..m]] in
head $ filter isPalindrome list
where
isPalindrome x = let s = show x in s == reverse s
euler5 = smallestMultiple 20
smallestMultiple :: Integral a => a -> a
smallestMultiple n = let list = [1..(n - 1)] in
smallestMultiple' n $ filter (\x -> all (\y -> y `mod` x /= 0 || x == y) list) list
where
smallestMultiple' n' list
| all (\x -> n' `mod` x == 0) list = n'
| otherwise = smallestMultiple' (n + n') list
euler5 = smallestMultiple 20
smallestMultiple :: Integral a => a -> a
smallestMultiple n = head $ filter (\c -> (all (\d -> c `mod` d == 0) divisors)) candidates
where
divisors =
let list = [1..(n - 1)] in
reverse $ (filter (\x -> all (\y -> y `mod` x /= 0 || x == y) list) list)
candidates = [n, (n * 2)..(foldl1 (*) divisors)]
-- ghc -O euler5-3.hs と「-O」最適化オプションをつけてコンパイルすることで、高速になる
main = print euler5
euler5 = smallestMultiple 20
smallestMultiple :: Integral a => a -> a
smallestMultiple n = head $ filter (\c -> (all (\d -> c `mod` d == 0) divisors)) candidates
where
divisors = take (fromIntegral n `div` 2) [(n - 1), (n -2)..1]
candidates = [n, (n * 2)..]
-- ghc -O euler5-4.hs と「-O」最適化オプションをつけてコンパイルすることで、高速になる
main = print euler5
euler5 = smallestMultiple 20
smallestMultiple :: Integral a => a -> a
smallestMultiple n = head [c| c <- [n, (n * 2)..], and [c `mod` d == 0| d <- divisors]]
where
divisors = take (fromIntegral n `div` 2) [(n - 1), (n -2)..1]
euler6 = (sumSquare 100) - (squareSum 100)
sumSquare :: (Enum a, Num a) => a -> a
sumSquare n = (foldl1 (+) [1..n]) ^ 2
squareSum :: (Enum a, Num a) => a -> a
squareSum n = foldl1 (+) [x ^ 2 |x <- [1..n]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment