Parallel calculations: Difference between revisions

→‎{{header|Perl 6}}: Add the missing helper functions.
(→‎{{header|Perl 6}}: Provide an example for parallel compution that works today.)
(→‎{{header|Perl 6}}: Add the missing helper functions.)
Line 1,404:
my \factories = @nums.race(:batch(@nums / 32)).map: *.&prime-factors.cache;
my $gmf = (factories»[0] »=>« @nums).reduce(&max).value;
 
sub prime-factors ( Int $n where * > 0 ) {
return $n if $n.is-prime;
return [] if $n == 1;
my $factor = find-factor( $n );
sort flat prime-factors( $factor ), prime-factors( $n div $factor );
}
 
sub find-factor ( Int $n, $constant = 1 ) {
my $x = 2;
my $rho = 1;
my $factor = 1;
while $factor == 1 {
$rho *= 2;
my $fixed = $x;
for ^$rho {
$x = ( $x * $x + $constant ) % $n;
$factor = ( $x - $fixed ) gcd $n;
last if 1 < $factor;
}
}
$factor = find-factor( $n, $constant + 1 ) if $n == $factor;
$factor;
}
</lang>
The second line takes the list of numbers and converts then to a <tt>RaceSeq</tt> that is stored in a raw variable. Any <tt>RaceSeq</tt> overloads <tt>map</tt> and <tt>grep</tt> to convert and pick values in worker threads. The runtime will pick the number of OS-level threads and assign worker threads to them while avoiding stalling in any part of the program. A <tt>RaceSeq</tt> is lazy, so the computation of values will happen in chunks as they are requested in the third line.
Anonymous user