View Category

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
perl
#!/usr/bin/perl
my @results;
for my $x (1..20) {
for my $y ($x..20) {
my $z = sqrt($x**2+$y**2);
push @results, [$x,$y,$z] if $z == int($z);
}
}
for my $triangle ( sort { $a->[2] <=> $b->[2] } @results) {
print "[".join(',',@$triangle)."]\n";
}
print
map"[".join(",",@$_{qw/x y z/})."]\n",
sort{ $$a{z}<=>$$b{z} }
grep{ $$_{z}=~/^\d+$/ }
map{my$x=$_;map{x=>$x,y=>$_,z=>sqrt($x*$x+$_*$_)},
($x..20)}(1..20);

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

perl
sub gcd {
my ($a, $b) = @_;
($a,$b) = ($b,$a) if $a > $b;

while ($a) { ($a, $b) = ($b % $a, $a) }

return $b;
}

print gcd( 8, 12 );
my $g = gcd (8, 12);
print $g;

sub gcd {
# Euclid's Algorithm - recursive
my ($c, $d) = @_;
return $c unless $d;
return gcd ($d, $c % $d);
}
my $g = gcd2 (8, 12);
print $g;

sub gcd2 {
# Dijkstra's Algorithm - recursive
my ($c, $d) = @_;
return $c if $c == $d;
return $c > $d? gcd2 ($c - $d, $d) : gcd2 ($c, $d - $c);
}