Project Euler 9: Pythagorean Triplets, Sum=1000

There is exactly one Pythagorean triplet (a^2+b^2=c^2) in which a+b+c=1000. Since all terms are positive, we can try all alternatives for 0 < a,b < 1000, which is less than 1000^2. This Perl script does it all:

1
2
3
4
5
6
7
8
9
10
11
12
# first, generate pairs of a and b
for ( my $a = 1; $a < 1000; $a++ ) {
        for ( my $b = $a; $b < 1000; $b++ ) {
                # c is then calculated from these
                my $c = sqrt( $a*$a + $b*$b );
                if ( $a+$b+$c == 1000 ) {
                        # print and exit if we found the answer
                        printf "%d*%d*%d=%d\n", $a, $b, $c, $a*$b*$c;
                        exit;
                }
        }
}

There is probably a faster solution without a square root, but this one is fast enough.

Maybe Related?

1 Comment »

  1. [...] &lt 1000, which is less than 10002. This perl script does it all: 1 2 3 4 5 6 7 8 9 10 11 12 first,http://timjoh.com/project-euler-9-pythagorean-triplets-sum1000/Foundations of Mac OS X Leopard Security Slashdotjsuda writes “At least a half-dozen times in the [...]

    Pingback by perl script — June 30, 2008 @ 2:04 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

FireStats iconAnvänder FireStats