Project Euler Problem 9

Special Pythagorean triplet

A Pythagorean triplet is a set of three natural numbers, a b c, for which,

a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Link to original description
Source code examples on Github

Erlang version

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname p9
% vim:syn=erlang

-mode(compile).

main(_) ->
    D = 1000,
    Answer = lists:last([ X*Y*(D-X-Y) || X <- lists:seq(1, D), Y <- lists:seq(1, D), X*X + Y*Y =:= (D-X-Y)*(D-X-Y)]),
    io:format("Answer: ~p ~n", [Answer]).

Erlang version (much efficient)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname p9_1
% vim:syn=erlang

-mode(compile).
-define(N, 1000).

main(_) ->
    io:format("Answer: ~p ~n", [a(1)]).

a(X) when X < ?N ->
    case b(X,X) of
        false -> a(X+1);
        Ret   -> Ret
    end.

b(X,Y) when Y < ?N, X*X+Y*Y =:= (?N-X-Y)*(?N-X-Y) -> X*Y*(?N-X-Y);
b(X,Y) when Y < ?N -> b(X,Y+1);
b(_,_) -> false.

Perl version

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/perl -w
use strict;

for my $a (1..1000){
    for my $b ($a..1000){
        my $c = 1000 - $a - $b;
        if($c > 0 && ($a*$a+$b*$b == $c*$c)){
            print "Answer: ".$a*$b*$c."\n";
            last;
        }
    }    
}

Python version

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/python

for a in xrange(1, 1000):
    for b in xrange(a, 1000):
        c = 1000 - a - b
        if c > 0:
            if c*c == a*a + b*b:
                answer = a*b*c
                print "Answer %d " % answer
                break