Law of cosines - triples: Difference between revisions

Added Perl example
(Added Perl example)
Line 506:
18394
[Finished in 3.444s]</pre>
 
=={{header|Perl}}==
{{trans|Perl 6}}
<lang perl>use utf8;
binmode STDOUT, "utf8:";
use Sort::Naturally;
 
sub triples {
my($n,$angle) = @_;
my(@triples,%sq);
my $sq{$_**2}=$_ for 1..$n;
for $a (1..$n-1) {
for $b ($a+1..$n) {
my $ab = $a*$a + $b*$b;
my $cos = $angle == 60 ? $ab - $a * $b :
$angle == 120 ? $ab + $a * $b :
$ab;
if ($angle == 60) {
push @triples, "$a $sq{$cos} $b" if exists $sq{$cos};
} else {
push @triples, "$a $b $sq{$cos}" if exists $sq{$cos};
}
}
}
@triples;
}
 
$n = 13;
say "Integer triangular triples for sides 1..$n:";
for my $angle (120, 90, 60) {
my @itt = triples($n,$angle);
if ($angle == 60) { push @itt, "$_ $_ $_" for 1..$n }
printf "Angle %3d° has %2d solutions: %s\n", $angle, scalar @itt,
join ', ', nsort @itt;
}
 
printf "Non-equilateral n=10000/60°: %d\n", scalar triples(10000,60);</lang>
{{out}}
<pre>Angle 120° has 2 solutions: 3 5 7, 7 8 13
Angle 90° has 3 solutions: 3 4 5, 6 8 10, 5 12 13
Angle 60° has 2 solutions: 1 1 1, 2 2 2, 3 3 3, 3 7 8, 4 4 4, 5 5 5, 5 7 8, 6 6 6, 7 7 7, 8 8 8, 9 9 9, 10 10 10, 11 11 11, 12 12 12, 13 13 13
Non-equilateral n=10000/60°: 18394</pre>
 
=={{header|Perl 6}}==
2,392

edits