Pythagorean triples: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) (→{{header|Perl 6}}: Add Perl 6 example) |
|||
Line 353: | Line 353: | ||
24, 32, 40 |
24, 32, 40 |
||
Up to a perimeter of 100, there are 17 triples, of which 7 are primitive.</pre> |
Up to a perimeter of 100, there are 17 triples, of which 7 are primitive.</pre> |
||
=={{header|Perl 6}}== |
|||
This is a fairly naive brute force implementation that is not really practical for large perimeter limits. 100 is no problem. 1000 is slow. 10000 is glacial. |
|||
Works with Rakudo 11.06. |
|||
<lang perl6>my %trips; |
|||
my $limit = 100; |
|||
for 3 .. $limit/2 -> $c { |
|||
for 1 .. $c-1 -> $a { |
|||
my $b = ($c ** 2 - $a **2).sqrt; |
|||
last if $c + $a + $b > $limit; |
|||
if $b == $b.Int { |
|||
my $key = ~($a, $b, $c).sort; |
|||
next if %trips.exists($key); |
|||
%trips{$key} = ([gcd] $c, $a, $b.Int) > 1 ?? 0 !! 1; |
|||
} |
|||
} |
|||
} |
|||
say "There are {+%trips.keys} Pythagorean Triples with a perimeter less than $limit," |
|||
~" of which {[+] %trips.values} are primitive."; |
|||
for %trips.keys.sort( {$^a.lc.subst(/(\d+)/,->$/{0~$0.chars.chr~$0},:g)} ) -> $k { |
|||
say $k.fmt("%14s"), %trips{$k} ?? ' - primitive' !! ''; |
|||
}</lang> |
|||
<pre>There are 17 Pythagorean Triples with a perimeter less than 100, of which 7 are primitive. |
|||
3 4 5 - primitive |
|||
5 12 13 - primitive |
|||
6 8 10 |
|||
7 24 25 - primitive |
|||
8 15 17 - primitive |
|||
9 12 15 |
|||
9 40 41 - primitive |
|||
10 24 26 |
|||
12 16 20 |
|||
12 35 37 - primitive |
|||
15 20 25 |
|||
15 36 39 |
|||
16 30 34 |
|||
18 24 30 |
|||
20 21 29 - primitive |
|||
21 28 35 |
|||
24 32 40</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |