From f98154f6478b68b76e64ae2a231c4849d5b9e44f Mon Sep 17 00:00:00 2001 From: Daniele Fucini Date: Sun, 10 Nov 2024 13:18:38 +0100 Subject: [PATCH] Add Haskell solution for Problem 12 --- Haskell/ProjectEuler.hs | 8 ++++++++ Haskell/p012.hs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 Haskell/p012.hs diff --git a/Haskell/ProjectEuler.hs b/Haskell/ProjectEuler.hs index 7741a1a..662263a 100644 --- a/Haskell/ProjectEuler.hs +++ b/Haskell/ProjectEuler.hs @@ -2,9 +2,11 @@ module ProjectEuler ( isPrime , digitSum , sumProperDivisors +, countDivisors ) where import Data.Char (digitToInt) +import Data.List (nub) isPrime :: (Integral n) => n -> Bool isPrime 1 = False @@ -22,3 +24,9 @@ digitSum n = sum $ map digitToInt $ show n 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 + + +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 + diff --git a/Haskell/p012.hs b/Haskell/p012.hs new file mode 100644 index 0000000..780adf1 --- /dev/null +++ b/Haskell/p012.hs @@ -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)