banovski

Project Euler, Problem #12, Haskell

Feb 26th, 2022 (edited)
948
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- The sequence of triangle numbers is generated by adding the natural
  2. -- numbers. So the 7th triangle number would be
  3. -- 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3,
  4. -- 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the
  5. -- first seven triangle numbers: 1: 1; 3: 1, 3; 6: 1, 2, 3, 6; 10: 1,
  6. -- 2, 5, 10; 15: 1, 3, 5, 15; 21: 1, 3, 7, 21; 28: 1, 2, 4, 7, 14, 28
  7. -- We can see that 28 is the first triangle number to have over five
  8. -- divisors. What is the value of the first triangle number to have
  9. -- over five hundred divisors?
  10.  
  11. -- Generate the infinite list of triangle numbers.
  12. tn :: [Integer]
  13. tn = scanl1 (+) [1 ..]
  14.  
  15. -- Take a number and return a tuple with the number and the number of
  16. -- its divisors.
  17. nad :: Integral c => c -> (c, Int)
  18. nad n = (n, d * 2 - sna)
  19.   where
  20.     d
  21.       | mod n 2 == 0 = length [q | q <- [1 .. srf n], mod n q == 0]
  22.       | otherwise = length [q | q <- [1,3 .. srf n], mod n q == 0]
  23.     srf = floor . sqrt . fromIntegral
  24.     src = ceiling . sqrt . fromIntegral
  25.     sna
  26.       | srf n /= src n = 0
  27.       | otherwise = 1
  28.  
  29. -- Check if the number of divisors is greater than five hundred.
  30. ndgfh :: (Ord a, Num a) => (t, a) -> Bool
  31. ndgfh (_, d)
  32.   | d > 500 = True
  33.   | otherwise = False
  34.  
  35. main :: IO ()
  36. main = print $ fst $ head $ filter ndgfh $ map nad tn
  37.  
  38. -- 76576500
  39.  
  40. -- real 0m8,009s
  41. -- user 0m7,966s
  42. -- sys  0m0,032s
Add Comment
Please, Sign In to add comment