Wednesday, November 9, 2011

Solution to Project Euler Problem 9 - Finding Pythagorean triplets

http://projecteuler.net/problem=9

Problem: 

A Pythagorean triplet is a set of three natural numbers, a < b < c, 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.

Answer:
    (200*200) + (375*375)) == (425 * 425)
      40000 + 140625 = 180625
        200 + 375 + 425 = 1000

Solution:
#!/usr/bin/perl -w
use strict;

my ($a,$b,$c,$ulimit);
$ulimit=1000;

print "Pythogon triplets \n";
for ($a=1;$a<=$ulimit;$a++)   {
  for ($b=1;$b<=$ulimit;$b++ ) {
    if ($a < $b ) {
      for ($c=1; $c<=$ulimit;$c++) {
        if ( $b < $c ) {
          if ( (($a*$a) + ($b*$b)) == ($c * $c) ) {
            print "  ($a*$a) + ($b*$b)) == ($c * $c) \n";
            my $aa=$a*$a;
            my $bb=$b*$b;
            my $cc=$c*$c;
            print "    $aa + $bb = $cc \n";
            if ( ($a + $b + $c) == 1000 ) {
                print "FOUND: $a + $b + $c = 1000 \n";
                exit(0);
            }
          }
        }
       }
    }
  }
}


No comments: