Skip to content

Instantly share code, notes, and snippets.

@zaneli
Last active August 29, 2015 13:56
Show Gist options
  • Save zaneli/8916634 to your computer and use it in GitHub Desktop.
Save zaneli/8916634 to your computer and use it in GitHub Desktop.
「HaskellでProject Euler(Problem 28~30)」ブログ用
main = print $ 1 + addDiags [2..1001*1001] 0 1 0
addDiags :: (Num a, Num b, Eq b) => [a] -> a -> Int -> b -> a
addDiags [] sum _ _ = sum
addDiags list sum step count = let (n:ns) = drop step' list in
addDiags ns (sum + n) step' count'
where
(step', count') | count == 4 = (step + 2, 1)
| otherwise = (step, count + 1)
main = print $ sumDiags 1001
sumDiags :: (Enum a, Eq a, Num a) => a -> a
sumDiags n = sum $ map sumDiag [1,3..n]
sumDiag :: (Enum a, Eq a, Num a) => a -> a
sumDiag 1 = 1
sumDiag n = let list = [((n-2)^2+1)..n^2] in sumDiag' ((length list `div` 4) - 1) list []
where
sumDiag' n xs result
| length xs > n = let (y:ys) = drop n xs in
sumDiag' n ys $ y:result
| otherwise = sum result
main = print $ sumDiags 1001
sumDiags :: (Enum a, Num a) => a -> a
sumDiags n = 1 + sum [4*m^2-6*(m-1) | m <- [3,5..n]]
import Data.List (nub, sort)
main = print $ length $ nub $ sort [a^b | a <- [2..100], b <- [2..100]]
import Data.Char (digitToInt)
import Data.List (find)
main = print $ answer 5
answer :: Integral a => a -> Int
answer n = sum $ filter (\n -> n == f n) [2..limit n]
where f = sum . map ((^n) . digitToInt) . show
limit :: Integral a => a -> Int
limit x = maybe 0 f $ find (\n -> f n < fill 9 n) [1..]
where f n = (n * (9 ^ x))
fill :: Num a => a -> Int -> a
fill n c = foldl1 (\a b -> a * 10 + b) $ take c $ repeat n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment