Skip to content

Project Euler, Problem 9, in Erlang

Problem 9, and more brute-forcey goodness for the solution.

“A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^(2) + b^(2) = c^(2)
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc."

I'm not totally happy with this one. I'm positive there is a better approach, and I'm particularly not happy with using a return value of "0" as a flag value. Feels wrong. I'll probably revisit this one.

Brute force, only optimization is on boundaries of the brute force test. Since A< B< C and A+B+C = 1000, A has to be less than 334 and B has to be less than 500.

Forceful code -

 -module(euler9).
 -export([triplet/0]).

triplet() ->
  Product = iteratea(333),
  Product.

iteratea(A)->
    if A >=1 ->
         Product = iterateb (A,499),
            if Product == 0 ->
               iteratea(A-1);
            true ->
               Product
            end;
    true ->
        0
    end.    

iterateb(A,B) ->
   if B > 1 ->
     C = 1000 – (A+B),
     if A*A + B*B == C*C ->
        io:format(“A ~w B ~w C ~w ~n”, [A,B,C]),
        A*B*C;
     true ->
        iterateb(A,B-1)
     end;
    true ->
       0
    end.

Post a Comment

Your email is never published nor shared. Required fields are marked *