From Ceyusa's blog:
"A Pythagorean triplet is a set of three natural numbers, a <>, 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."
My Perl solution (ok it isn't a functional programming but works):
#!/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.