Pythagorean triples: Difference between revisions
Content added Content deleted
m (→{{header|Java}}: Added link to new brute force version) |
Thundergnat (talk | contribs) m (→{{header|Perl 6}}: Tweak brute-force example a bit) |
||
Line 461: | Line 461: | ||
First up 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. |
First up 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 |
Works with Rakudo 2011.06. |
||
<lang perl6>my % |
<lang perl6>my %triples; |
||
my $limit = 100; |
my $limit = 100; |
||
for 3 .. $limit/2 -> $c { |
for 3 .. $limit/2 -> $c { |
||
for 1 .. $c |
for 1 .. $c -> $a { |
||
my $b = ($c |
my $b = ($c * $c - $a * $a).sqrt; |
||
last if $c + $a + $b > $limit; |
last if $c + $a + $b > $limit; |
||
last if $a > $b; |
|||
if $b == $b.Int { |
if $b == $b.Int { |
||
my $key = |
my $key = "$a $b $c"; |
||
%triples{$key} = ([gcd] $c, $a, $b.Int) > 1 ?? 0 !! 1; |
|||
% |
say $key, %triples{$key} ?? ' - primitive' !! ''; |
||
} |
} |
||
} |
} |
||
} |
} |
||
say "There are {+% |
say "There are {+%triples.keys} Pythagorean Triples with a perimeter <= $limit," |
||
~" |
~"\nof which {[+] %triples.values} are primitive.";</lang> |
||
⚫ | |||
for %trips.keys.sort( {$^a.lc.subst(/(\d+)/,->$/{0~$0.chars.chr~$0},:g)} ) -> $k { |
|||
⚫ | |||
say $k.fmt("%14s"), %trips{$k} ?? ' - primitive' !! ''; |
|||
⚫ | |||
}</lang> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
7 24 25 - primitive |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
20 21 29 - primitive |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
12 35 37 - primitive |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
</pre> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
Here's a much faster version. Hint, "oyako" is Japanese for "parent/child". <tt>:-)</tt> |
Here's a much faster version. Hint, "oyako" is Japanese for "parent/child". <tt>:-)</tt> |
||
{{works with|niecza}} |
{{works with|niecza}} |