Advertisement
banovski

Project Euler, Problem #6, Haskell

Dec 13th, 2021 (edited)
1,597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Find the difference between the sum of the squares of the first one
  2. -- hundred natural numbers and the square of the sum.
  3.  
  4. -- Solution #1
  5.  
  6. main :: IO ()
  7. main = print $ sum [1 .. 100] ^ 2 - sum [x ^ 2 | x <- [1 .. 100]]
  8.  
  9. -- 25164150
  10.  
  11. -- real 0m0,003s
  12. -- user 0m0,000s
  13. -- sys  0m0,003s
  14.  
  15. -- Solution #2
  16.  
  17. main :: IO ()
  18. main = print $ foldl (+) 0 [1 .. 100] ^ 2 - foldl (+) 0 (map (^ 2) [1 .. 100])
  19.  
  20. -- 25164150
  21.  
  22. -- real 0m0,007s
  23. -- user 0m0,003s
  24. -- sys  0m0,001s
  25.  
  26. -- Solution #3
  27.  
  28. check :: (Num a, Ord a) => a -> a -> a -> a
  29. check d s t =
  30.   if d > 0
  31.     then pow (d - 1) d t
  32.     else t
  33.  
  34. pow :: (Num a, Ord a) => a -> a -> a -> a
  35. pow d s = accum d (s ^ 2)
  36.  
  37. accum :: (Num a, Ord a) => a -> a -> a -> a
  38. accum d s t = check d s (t + s)
  39.  
  40. sumRange :: (Ord t, Num t) => t -> t -> t
  41. sumRange d t =
  42.   if d > 0
  43.     then sumRange (d - 1) (t + d)
  44.     else t
  45.  
  46. main :: IO ()
  47. main = print $ sumRange 100 0 ^ 2 - check 100 0 0
  48.  
  49. -- 25164150
  50.  
  51. -- real 0m0,007s
  52. -- user 0m0,003s
  53. -- sys  0m0,001s
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement