HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Project Euler #9 in haskell

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
projecteulerhaskell

Problem

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 ]

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#15657, answer score: 3

Revisions (0)

No revisions yet.