Jump to content

Pythagorean triples: Difference between revisions

m
→‎{{header|Perl 6}}: Tweak brute-force example a bit
m (→‎{{header|Java}}: Added link to new brute force version)
m (→‎{{header|Perl 6}}: Tweak brute-force example a bit)
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.
 
Works with Rakudo 112011.06.
 
<lang perl6>my %tripstriples;
my $limit = 100;
 
for 3 .. $limit/2 -> $c {
for 1 .. $c-1 -> $a {
my $b = ($c ** 2$c - $a **2 $a).sqrt;
last if $c + $a + $b > $limit;
last if $a > $b;
if $b == $b.Int {
my $key = ~("$a, $b, $c).sort";
next%triples{$key} if= %trips.exists([gcd] $keyc, $a, $b.Int) > 1 ?? 0 !! 1;
say $key, %tripstriples{$key} = ([gcd] $c, $a, $b.Int) > 1 ?? 0' - primitive' !! 1'';
}
}
}
 
say "There are {+%tripstriples.keys} Pythagorean Triples with a perimeter less than<= $limit,"
~" of\nof which {[+] %tripstriples.values} are primitive.";</lang>
 
<pre>3 4 5 - primitive
for %trips.keys.sort( {$^a.lc.subst(/(\d+)/,->$/{0~$0.chars.chr~$0},:g)} ) -> $k {
6 8 10
say $k.fmt("%14s"), %trips{$k} ?? ' - primitive' !! '';
5 12 35 3713 - primitive
}</lang>
9 12 15
 
8 15 7 24 2517 - primitive
<pre>There are 17 Pythagorean Triples with a perimeter less than 100, of which 7 are primitive.
12 16 20
3 4 5 - primitive
7 24 5 12 1325 - primitive
15 20 25
6 8 10
10 24 26
7 24 25 - primitive
20 21 8 15 1729 - primitive
18 24 30
9 12 15
16 30 34
9 40 41 - primitive
21 28 35
10 24 26
12 35 37 - primitive
12 16 20
15 36 39
12 35 37 - primitive
24 32 40</pre>
15 20 25
9 40 41 - primitive
15 36 39
<pre>There are 17 Pythagorean Triples with a perimeter less than<= 100, of which 7 are primitive.
16 30 34
of which 207 21 29 -are primitive.
18 24 30
</pre>
20 21 29 - primitive
21 28 35
24 32 40</pre>
Here's a much faster version. Hint, "oyako" is Japanese for "parent/child". <tt>:-)</tt>
{{works with|niecza}}
10,339

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.