Problem 9: Pythagorean triplets.
Project Euler problem 9 is back in proper maths mode with this beauty:
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Wow. Numbers are strange. Their relationships inscrutable and powerful. Euclid sorted this one out some time ago so I just stood on his giant shoulders (well, Wikipedia's actually) and had this for generating triplets:
generate_triple(M, N) ->
A = 2 * (M*N),
B = (M*M) - (N*N),
C = (M*M) + (N*N),
{A, B, C}.
Now, my friend Nick at work managed to express C in terms of A and B and save himself the trouble of the above but he is smarter and better educated than me (though I doubt he can do a short 21 for a 10 mile TT so I can comfort myself there).
The rest of the work is more brute force but Erlang does the heavy lifting for me:
prob9() ->
L = [generate_triple(M, N) || N <- lists:seq(1,100), M <- lists:seq(2, 100), M > N],
[{A,B,C}] = lists:filter(fun({A,B,C}) -> A+B+C =:= 1000 end, L),
A*B*C.
I love the second line. The power of pattern matching is clear and it creates a readable, uncluttered way to get at the values of A, B and C. The question "...There exists exactly one..." assures me that [{A,B,C}] will match.
Again, Nick's Java effort is more optimal (he doesn't do the 2 loops (he needs a blog I guess)).