Pythagorean triples: Difference between revisions

Content added Content deleted
m (→‎{{header|Java}}: Added link to new brute force version)
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 11.06.
Works with Rakudo 2011.06.


<lang perl6>my %trips;
<lang perl6>my %triples;
my $limit = 100;
my $limit = 100;


for 3 .. $limit/2 -> $c {
for 3 .. $limit/2 -> $c {
for 1 .. $c-1 -> $a {
for 1 .. $c -> $a {
my $b = ($c ** 2 - $a **2).sqrt;
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 = ~($a, $b, $c).sort;
my $key = "$a $b $c";
next if %trips.exists($key);
%triples{$key} = ([gcd] $c, $a, $b.Int) > 1 ?? 0 !! 1;
%trips{$key} = ([gcd] $c, $a, $b.Int) > 1 ?? 0 !! 1;
say $key, %triples{$key} ?? ' - primitive' !! '';
}
}
}
}
}
}


say "There are {+%trips} Pythagorean Triples with a perimeter less than $limit,"
say "There are {+%triples.keys} Pythagorean Triples with a perimeter <= $limit,"
~" of which {[+] %trips.values} are primitive.";
~"\nof which {[+] %triples.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 13 - primitive
}</lang>
9 12 15

8 15 17 - 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
5 12 13 - primitive
7 24 25 - primitive
15 20 25
6 8 10
10 24 26
7 24 25 - primitive
8 15 17 - primitive
20 21 29 - 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
15 20 25
9 40 41 - primitive
15 36 39
There are 17 Pythagorean Triples with a perimeter <= 100,
16 30 34
of which 7 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>
Here's a much faster version. Hint, "oyako" is Japanese for "parent/child". <tt>:-)</tt>
{{works with|niecza}}
{{works with|niecza}}