Pythagorean triples: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: add vectorized version)
(→‎{{header|Perl 6}}: typos, more explanation)
Line 469: Line 469:


for 10,100,1000 ... * -> $limit {
for 10,100,1000 ... * -> $limit {
say triples $limit;</lang>
say triples $limit;
}</lang>
Output:
Output:
<pre>10 => (0 0)
<pre>10 => (0 0)
100 => (7 17)
100 => (7 17)
1000 => (70 325)
1000 => (70 32510000 => (703 4858)
10000 => (703 4858)
100000 => (7026 64741)
100000 => (7026 64741)
1000000 => (70229 808950)
1000000 => (70229 808950)
10000000 => (702309 9706567)
10000000 => (702309 9706567)
^C</pre>
^C</pre>
Note the cute trick of adding complex numbers to add two numbers in parallel. Also, it will continue on forever, so eventually when you get tired of thrashing (at about 100 million on my computer), you can just stop it.
Note the cute trick of adding complex numbers to add two numbers in parallel. Also, the geometric sequence of limits will continue on forever, so eventually when you get tired of thrashing (at about 100 million on my computer), you can just stop it. Another efficiency trick of note: we avoid passing the limit in as a parameter to the inner helper routine, but instead supply the limit via the lexical scope. The use of <tt>gather</tt>/<tt>take</tt> allows the summation to run in a different thread than the helper function, at least in theory...


Here is an alternate version that avoids naming any scalars that can be handled by vector processing instead:
Here is an alternate version that avoids naming any scalars that can be handled by vector processing instead:
Line 487: Line 487:


sub triples($limit) {
sub triples($limit) {

sub oyako(@trippy) {
sub oyako(@trippy) {
my $perim = [+] @trippy;
my $perim = [+] @trippy;
Line 504: Line 505:
say triples $limit;
say triples $limit;
}</lang>
}</lang>
Using vectorized ops allows a bit more potential for parallelization, though this is probably not as big a win in this case, especially since we do a certain amount of multiplying by 1 that the scalar version doesn't need to do.


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