"A Pythagorean triplet is a set of three natural numbers, `a <>, for which, a^{2} + b^{2} = c^{2}`

For example, 3^{2} + 4^{2} = 9 + 16 = 25 = 5^{2}.

There exists exactly one Pythagorean triplet for which `a` + `b` + `c` = 1000.

Find the product `abc`."

#!/usr/bin/perl -w

use strict;

my @n = ( 1 .. 1000 );

foreach my $a ( @n ) {

my $a2 = $a * $a;

foreach my $b ( @n ) {

my $b2 = $b * $b;

my $c = sqrt ( $a2 + $b2 );

next unless ( ($a + $b + $c) == 1000 );

next unless ( ($c / int $c ) == 1 );

print "Solution: a = $a b = $b c = $c\n";

exit;

}

}

But I thinks there's a problem: is computational expensive, because it doesn't honor the requirement a < b < c, so the script burns cpu cycles in no valid solution searchs.

ReplyDeleteWell I agree with you, it is a force-brute system, specially because only one solution is possible when it find it exit (in your blog I did not include this), also I don't include the "a lt b lt c" test, but it's fast, 0.1 sec in real time.

ReplyDeleteSee you.