Add Haskell solution for Problem 12
This commit is contained in:
parent
dcf2d68b0e
commit
f98154f647
@ -2,9 +2,11 @@ module ProjectEuler
|
|||||||
( isPrime
|
( isPrime
|
||||||
, digitSum
|
, digitSum
|
||||||
, sumProperDivisors
|
, sumProperDivisors
|
||||||
|
, countDivisors
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Data.Char (digitToInt)
|
import Data.Char (digitToInt)
|
||||||
|
import Data.List (nub)
|
||||||
|
|
||||||
isPrime :: (Integral n) => n -> Bool
|
isPrime :: (Integral n) => n -> Bool
|
||||||
isPrime 1 = False
|
isPrime 1 = False
|
||||||
@ -22,3 +24,9 @@ digitSum n = sum $ map digitToInt $ show n
|
|||||||
|
|
||||||
sumProperDivisors :: (Integral a) => a -> a
|
sumProperDivisors :: (Integral a) => a -> a
|
||||||
sumProperDivisors n = sum [ if x /= y then x + y else x | x <- [2..ceiling $ sqrt $ fromIntegral n], let y = n `div` x, n `mod` x == 0 ] + 1
|
sumProperDivisors n = sum [ if x /= y then x + y else x | x <- [2..ceiling $ sqrt $ fromIntegral n], let y = n `div` x, n `mod` x == 0 ] + 1
|
||||||
|
|
||||||
|
|
||||||
|
countDivisors :: (Integral a) => a -> Int
|
||||||
|
countDivisors n = length $ nub $ concat [ [x, n `div` x] | x <- [1..limit], n `mod` x == 0 ]
|
||||||
|
where limit = floor $ sqrt $ fromIntegral n
|
||||||
|
|
||||||
|
33
Haskell/p012.hs
Normal file
33
Haskell/p012.hs
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
-- The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
|
||||||
|
-- The first ten terms would be:
|
||||||
|
--
|
||||||
|
-- 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
|
||||||
|
--
|
||||||
|
-- Let us list the factors of the first seven triangle numbers:
|
||||||
|
--
|
||||||
|
-- 1: 1
|
||||||
|
-- 3: 1,3
|
||||||
|
-- 6: 1,2,3,6
|
||||||
|
-- 10: 1,2,5,10
|
||||||
|
-- 15: 1,3,5,15
|
||||||
|
-- 21: 1,3,7,21
|
||||||
|
-- 28: 1,2,4,7,14,28
|
||||||
|
--
|
||||||
|
-- We can see that 28 is the first triangle number to have over five divisors.
|
||||||
|
--
|
||||||
|
-- What is the value of the first triangle number to have over five hundred divisors?
|
||||||
|
|
||||||
|
import Data.List (nub)
|
||||||
|
|
||||||
|
import ProjectEuler (countDivisors)
|
||||||
|
|
||||||
|
triangNumbers :: [Int]
|
||||||
|
triangNumbers = scanl1 (+) [1..]
|
||||||
|
|
||||||
|
triang500 :: Int
|
||||||
|
triang500 = head [ x | x <- triangNumbers, countDivisors x > 500 ]
|
||||||
|
|
||||||
|
main = do
|
||||||
|
let result = triang500
|
||||||
|
putStrLn $ "Project Euler, Problem 12\n"
|
||||||
|
++ "Answer: " ++ (show result)
|
Loading…
x
Reference in New Issue
Block a user