Advertisement
banovski

Project Euler, Problem #9, Haskell

Feb 4th, 2022 (edited)
1,618
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- A Pythagorean triplet is a set of three natural numbers, a < b < c,
  2. -- for which, a^2 + b^2 = c^2. For example,
  3. -- 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean
  4. -- triplet for which a + b + c = 1000. Find the product abc.
  5.  
  6. -- A more efficient solution
  7.  
  8. ac :: Integral t => t -> [t]
  9. ac c =
  10.   [ a * b * c
  11.   | a <- [1 .. div (1000 - c) 2 - 1]
  12.   , let b = (1000 - c) - a
  13.   , a ^ 2 + b ^ 2 == c ^ 2
  14.   ]
  15.  
  16. main :: IO ()
  17. main = print $ head $ concatMap ac [997,996 .. 3]
  18.  
  19. -- 31875000
  20.  
  21. -- real 0m0,330s
  22. -- user 0m0,317s
  23. -- sys  0m0,012s
  24.  
  25. -- ################################################################################################
  26.  
  27. -- A less efficient solution
  28.  
  29. main :: IO ()
  30. main =
  31.   print $
  32.   head
  33.     [ x * y * z
  34.     | x <- [1 .. 1000]
  35.     , y <- [1 .. 1000]
  36.     , let z = 1000 - (x + y)
  37.     , x + y + z == 1000
  38.     , x ^ 2 + y ^ 2 == z ^ 2
  39.     , x < y && y < z
  40.     ]
  41.  
  42. -- 31875000
  43.  
  44. -- real 0m0,782s
  45. -- user 0m0,777s
  46. -- sys  0m0,004s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement