5
\$\begingroup\$

I am trying to teach myself haskell by means of project Euler

i sovled problem #9 by means of this code which is on the brute force side I was wondering if there is a more elegant/haskell/efficient solution

let project_euler_9 = [(a,b,c) | c <- [1..500], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c==1000 ] 
konijn
34.2k5 gold badges70 silver badges267 bronze badges
asked Sep 15, 2012 at 22:21
\$\endgroup\$
4
  • \$\begingroup\$ Your solution main not be the fastest one but it's easy to read. Here's another solution. Also, shouldn't you return the product of (a*b*c)? \$\endgroup\$ Commented Sep 16, 2012 at 7:56
  • \$\begingroup\$ There are formulas to enumerate all pythagorean triples. You can use them to reduce the search space. \$\endgroup\$ Commented Sep 16, 2012 at 9:24
  • \$\begingroup\$ One thing that you could do is filter the list, a, b, c, to contain only values that have a integer as the square root. \$\endgroup\$ Commented Sep 18, 2012 at 3:21
  • 1
    \$\begingroup\$ Consider the order of the conditions a+b+c==1000 and a^2+b^2 == c^2 and how that order might affect run time. Also, from a+b+c == 1000 you can replace a <- [1..b] with a = 1000-b-c. \$\endgroup\$ Commented Oct 3, 2012 at 21:25

1 Answer 1

3
\$\begingroup\$

As already mentioned there are formulas for enumerating the pythagorean triples, but your solution can be made quite fast by bounding the search space more. You have already taken care of the symmetry in the solutions by letting a be less then b (a <- [1..b]), but note that since a + b + c == 1000, once you know the value of a and b you know that c = 1000 - a - b so you only need to check that one case:

[(a,b,c) | a <- [1..500], b <- [1..a], let c = 1000 - a - b, a^2 + b^2 == c^2]

The above code runs in less then a second on my machine with GHCi.

answered Oct 7, 2012 at 11:05
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.