Law of cosines - triples: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: Break apart angle calculations to reduce branching logic, clean up unneeded variables, eke out a few more percent points of speed-up)
Line 578: Line 578:


=={{header|Perl 6}}==
=={{header|Perl 6}}==
<lang perl6>sub triples ($n, $angle where any(60,90,120)) {
<lang perl6>multi triples (60, $n) {
my %sq = (1..$n).map: { .² => $_ };
my %sq = (1..$n).map: { .² => $_ };
my %triples;
my %triples;
(1..^$n).race(:8degree).map: -> $a {
(1..^$n).race(:8degree).map: -> $a {
for $a^..$n -> $b {
for $a^..$n -> $b {
my $ab = $a * $a + $b * $b;
my $cos = $a * $a + $b * $b - $a * $b;
my $cos = $angle == 60 ?? $ab - $a * $b !!
%triples{~($a, %sq{$cos}, $b)}++ and last if %sq{$cos}:exists;
$angle == 120 ?? $ab + $a * $b !!
$ab;
if $angle == 60 {
%triples{$angle}{~($a, %sq{$cos}, $b)}++ and last if %sq{$cos}:exists;
}
else {
%triples{$angle}{~($a, $b, %sq{$cos})}++ and last if %sq{$cos}:exists;
}
}
}
}
}
%triples
%triples.keys
}

multi triples (90, $n) {
my %sq = (1..$n).map: { .² => $_ };
my %triples;
(1..^$n).race(:8degree).map: -> $a {
for $a^..$n -> $b {
my $cos = $a * $a + $b * $b;
%triples{~($a, $b, %sq{$cos})}++ and last if %sq{$cos}:exists;
}
}
%triples.keys
}

multi triples (120, $n) {
my %sq = (1..$n).map: { .² => $_ };
my %triples;
(1..^$n).race(:8degree).map: -> $a {
for $a^..$n -> $b {
my $cos = $a * $a + $b * $b + $a * $b;
%triples{~($a, $b, %sq{$cos})}++ and last if %sq{$cos}:exists;
}
}
%triples.keys
}
}


Line 603: Line 619:
say "Integer triangular triples for sides 1..$n:";
say "Integer triangular triples for sides 1..$n:";
for 120, 90, 60 -> $angle {
for 120, 90, 60 -> $angle {
my %itt = triples($n, $angle);
my @itt = triples($angle, $n);
if $angle == 60 { push %itt<60>, "$_ $_ $_" => 1 for 1..$n }
if $angle == 60 { push @itt, "$_ $_ $_" for 1..$n }
printf "Angle %3d° has %2d solutions: %s\n", $angle, +%itt{$angle}, %itt{$angle}.keys.sort(*.&naturally).join(', ');
printf "Angle %3d° has %2d solutions: %s\n", $angle, +@itt, @itt.sort(*.&naturally).join(', ');
}
}


my ($angle, $count) = 60, 10_000;
my ($angle, $count) = 60, 10_000;
say "\nExtra credit:";
say "\nExtra credit:";
print "Number of 60° integer triples in the range 1..$count where the sides are not all the same length: ";
say "$angle° integer triples in the range 1..$count where the sides are not all the same length: ", +triples($angle, $count);</lang>
say +triples($count, $angle){$angle};</lang>
{{out}}
{{out}}
<pre>Integer triangular triples for sides 1..13:
<pre>Integer triangular triples for sides 1..13:
Line 619: Line 634:


Extra credit:
Extra credit:
Number of 60° integer triples in the range 1..10000 where the sides are not all the same length: 18394</pre>
60° integer triples in the range 1..10000 where the sides are not all the same length: 18394</pre>


=={{header|Python}}==
=={{header|Python}}==