Parallel calculations: Difference between revisions

Added FreeBASIC
(Added FreeBASIC)
 
(45 intermediate revisions by 19 users not shown)
Line 29:
 
prime_numbers.ads:
<langsyntaxhighlight Adalang="ada">generic
type Number is private;
Zero : Number;
Line 50:
end Calculate_Factors;
 
end Prime_Numbers;</langsyntaxhighlight>
 
prime_numbers.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
package body Prime_Numbers is
 
Line 102:
end Calculate_Factors;
 
end Prime_Numbers;</langsyntaxhighlight>
 
Example usage:
 
parallel.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Prime_Numbers;
procedure Parallel is
Line 160:
Ada.Text_IO.New_Line;
end;
end Parallel;</langsyntaxhighlight>
 
{{out}}
Line 175:
For that matter, the code uses the dumbest prime factoring method,
and doesn't even test if the numbers can be divided by 2.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <omp.h>
 
Line 207:
printf("Largest factor: %d of %d\n", largest_factor, largest);
return 0;
}</langsyntaxhighlight>
{{out}} (YMMV regarding the order of output):
<pre>thread 1: found larger: 47 of 12878893
Line 217:
thread 1: not larger: 3 of 12757923
Largest factor: 47 of 12878893</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
public static List<int> PrimeFactors(int number)
{
var primes = new List<int>();
for (int div = 2; div <= number; div++)
{
while (number % div == 0)
{
primes.Add(div);
number = number / div;
}
}
return primes;
}
 
static void Main(string[] args)
{
int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 };
// Calculate each of those numbers' prime factors, in parallel
var factors = n.AsParallel().Select(PrimeFactors).ToList();
// Make a new list showing the smallest factor for each
var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList();
// Find the index that corresponds with the largest of those factors
int biggestFactor = smallestFactors.Max();
int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor);
Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor);
Console.WriteLine(string.Join(" ", factors[whatIndexIsThat]));
}
}</syntaxhighlight>
{{out}}
<pre>12878611 has the largest minimum prime factor: 47
47 101 2713</pre>
 
Another version, using Parallel.For:
 
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
private static void Main(string[] args)
{
int j = 0, m = 0;
decimal[] n = {12757923, 12878611, 12757923, 15808973, 15780709, 197622519};
var l = new List<int>[n.Length];
 
Parallel.For(0, n.Length, i => { l[i] = getPrimes(n[i]); });
 
for (int i = 0; i<n.Length; i++)
if (l[i].Min()>m)
{
m = l[i].Min();
j = i;
}
 
Console.WriteLine("Number {0} has largest minimal factor:", n[j]);
foreach (int list in l[j])
Console.Write(" "+list);
}</syntaxhighlight>
{{out}}
<pre>Number 12878611 has largest minimal factor:
47 101 2713</pre>
 
=={{header|C++}}==
Line 223 ⟶ 292:
This uses C++11 features including lambda functions.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iterator>
#include <vector>
Line 279 ⟶ 348:
});
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 285 ⟶ 354:
12878893 = [ 47 274019 ]
</pre>
 
=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
public static List<int> PrimeFactors(int number)
{
var primes = new List<int>();
for (int div = 2; div <= number; div++)
{
while (number % div == 0)
{
primes.Add(div);
number = number / div;
}
}
return primes;
}
 
static void Main(string[] args)
{
int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 };
// Calculate each of those numbers' prime factors, in parallel
var factors = n.AsParallel().Select(PrimeFactors).ToList();
// Make a new list showing the smallest factor for each
var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList();
// Find the index that corresponds with the largest of those factors
int biggestFactor = smallestFactors.Max();
int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor);
Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor);
Console.WriteLine(string.Join(" ", factors[whatIndexIsThat]));
}
}</lang>
{{out}}
<pre>12878611 has the largest minimum prime factor: 47
47 101 2713</pre>
 
Another version, using Parallel.For:
 
<lang csharp>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
private static void Main(string[] args)
{
int j = 0, m = 0;
decimal[] n = {12757923, 12878611, 12757923, 15808973, 15780709, 197622519};
var l = new List<int>[n.Length];
 
Parallel.For(0, n.Length, i => { l[i] = getPrimes(n[i]); });
 
for (int i = 0; i<n.Length; i++)
if (l[i].Min()>m)
{
m = l[i].Min();
j = i;
}
 
Console.WriteLine("Number {0} has largest minimal factor:", n[j]);
foreach (int list in l[j])
Console.Write(" "+list);
}</lang>
{{out}}
<pre>Number 12878611 has largest minimal factor:
47 101 2713</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(use '[clojure.contrib.lazy-seqs :only [primes]])
 
(defn lpf [n]
Line 369:
(apply max-key second)
println
time)</langsyntaxhighlight>
{{out}}
<pre>[99847 313]
Line 376:
=={{header|Common Lisp}}==
Depends on quicklisp.
<langsyntaxhighlight lang="lisp">(ql:quickload '(lparallel))
 
(setf lparallel:*kernel* (lparallel:make-kernel 4)) ;; Configure for your system.
Line 400:
 
(defun print-max-factor (pair)
(format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">CL-USER> (print-max-factor (max-minimum-factor '(12757923 12878611 12878893 12757923 15808973 15780709 197622519)))
12878893 has the largest minimum factor 47</langsyntaxhighlight>
 
=={{header|D}}==
===Using Eager Parallel Map===
<langsyntaxhighlight lang="d">ulong[] decompose(ulong n) pure nothrow {
typeof(return) result;
for (ulong i = 2; n >= i * i; i++)
Line 432:
auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1]));
writeln("N. with largest min factor: ", pairs.reduce!max[1]);
}</langsyntaxhighlight>
{{out}}
<pre>N. with largest min factor: 7310027617718202995</pre>
 
===Using Threads===
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.typecons,
core.thread, core.stdc.time;
 
Line 521:
writefln("Number with largest min. factor is %16d," ~
" with factors:\n\t%s", maxMin.tupleof);
}</langsyntaxhighlight>
{{out}} (1 core CPU, edited to fit page width):
<pre>Minimum factors for respective numbers are:
Line 536:
Number with largest min. factor is 115797840077099, with factors:
[544651, 212609249]</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Threading}}
{{libheader| Velthuis.BigIntegers}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Parallel_calculations;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Threading,
Velthuis.BigIntegers;
 
function IsPrime(n: BigInteger): Boolean;
var
i: BigInteger;
begin
if n <= 1 then
exit(False);
 
i := 2;
while i < BigInteger.Sqrt(n) do
begin
if n mod i = 0 then
exit(False);
inc(i);
end;
 
Result := True;
end;
 
function GetPrimes(n: BigInteger): TArray<BigInteger>;
var
divisor, next, rest: BigInteger;
begin
divisor := 2;
next := 3;
rest := n;
while (rest <> 1) do
begin
while (rest mod divisor = 0) do
begin
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := divisor;
rest := rest div divisor;
end;
divisor := next;
next := next + 2;
end;
end;
 
function Min(l: TArray<BigInteger>): BigInteger;
begin
if Length(l) = 0 then
exit(0);
 
Result := l[0];
for var v in l do
if v < result then
Result := v;
end;
 
const
n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519];
 
var
m: BigInteger;
len, j, i: Uint64;
l: TArray<TArray<BigInteger>>;
 
begin
j := 0;
m := 0;
len := length(n);
SetLength(l, len);
 
TParallel.for (0, len - 1,
procedure(i: Integer)
begin
l[i] := getPrimes(n[i]);
end);
 
for i := 0 to len - 1 do
begin
var _min := Min(l[i]);
if _min > m then
begin
m := _min;
j := i;
end;
end;
 
writeln('Number ', n[j].ToString, ' has largest minimal factor:');
for var v in l[j] do
write(' ', v.ToString);
 
readln;
end.</syntaxhighlight>
 
=={{header|Erlang}}==
Perhaps it is of interest that the code will handle exceptions correctly. If the function (in this case factors/1) throws an exception, then the task will get it. I had to copy factors/1 from [[Prime_decomposition]] since it is only a fragment, not a complete example.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( parallel_calculations ).
 
Line 582 ⟶ 682:
My_pid ! Result
end ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
8> parallel_calculations:task().
12878611 has largest minimal factor among its prime factors [2713,101,47]
</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System
open PrimeDecomp // Has the decompose function from the Prime decomposition task
 
let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L]
let decomp num = decompose num 2L
 
let largestMinPrimeFactor (numbers: int64 list) =
let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] // Compute the number and its prime decomposition list
|> Async.RunSynchronously // Start and wait for all parallel computations to complete.
|> Array.sortBy (snd >> List.min >> (~-)) // Sort in descending order, based on the min prime decomp number.
decompDetails.[0]
 
let showLargestMinPrimeFactor numbers =
let number, primeList = largestMinPrimeFactor numbers
printf "Number %d has largest minimal factor:\n " number
List.iter (printf "%d ") primeList
 
showLargestMinPrimeFactor data</syntaxhighlight>
 
{{out}}
<pre>
Number 115797840077099 has largest minimal factor:
544651 212609249
</pre>
 
Line 592 ⟶ 719:
===Manual Thread Management===
 
<langsyntaxhighlight lang="factor">
USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ;
IN: <filename>
Line 611 ⟶ 738:
"Number with largest min. factor is " swap number>string append
", with factors: " append write .
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 618 ⟶ 745:
 
===With Concurency Module===
<langsyntaxhighlight lang="factor">
USING: kernel io prettyprint sequences arrays math.primes.factors math.parser concurrency.combinators ;
{ 576460752303423487 576460752303423487 576460752303423487 112272537195293
Line 626 ⟶ 753:
"Number with largest min. factor is " swap number>string append
", with factors: " append write .
</syntaxhighlight>
</lang>
{{out}}
<pre>
Number with largest min. factor is 115797840077099, with factors: { 544651 212609249 }
</pre>
 
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
open PrimeDecomp // Has the decompose function from the Prime decomposition task
 
let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L]
let decomp num = decompose num 2L
 
let largestMinPrimeFactor (numbers: int64 list) =
let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] // Compute the number and its prime decomposition list
|> Async.RunSynchronously // Start and wait for all parallel computations to complete.
|> Array.sortBy (snd >> List.min >> (~-)) // Sort in descending order, based on the min prime decomp number.
decompDetails.[0]
 
let showLargestMinPrimeFactor numbers =
let number, primeList = largestMinPrimeFactor numbers
printf "Number %d has largest minimal factor:\n " number
List.iter (printf "%d ") primeList
 
showLargestMinPrimeFactor data</lang>
 
{{out}}
<pre>
Number 115797840077099 has largest minimal factor:
544651 212609249
</pre>
 
 
=={{header|Fortran}}==
Line 664 ⟶ 763:
Using OpenMP (compile with -fopenmp)
 
<langsyntaxhighlight lang="fortran">
program Primes
 
Line 719 ⟶ 818:
 
end program Primes
</syntaxhighlight>
</lang>
 
{{out}}
Line 731 ⟶ 830:
Thread 0: 15780709 7 17 132611
12878611 have the Largest factor: 47</pre>
 
=={{header|FreeBASIC}}==
FreeBASIC does not have native support for parallel or multithreaded programming.
However, you can use external C libraries that provide multithreading functionality,
such as the POSIX threading library (pthreads) or the Windows threading library.
 
Here's a basic example of how you could use the pthreads library in FreeBASIC:
<syntaxhighlight lang="vbnet">#ifdef __FB_WIN32__
' ... instructions only for Win ...
#Include "windows.bi"
Function ThreadFunc As Dword Cdecl Alias "ThreadFunc"(param As Any Ptr) Export
Print "Thread running"
Function = 0
End Function
Dim As HANDLE thread
Dim As Dword threadId
thread = CreateThread(NULL, 0, @ThreadFunc, NULL, 0, @threadId)
If thread = NULL Then
Print "Error creating thread"
Sleep
End 1
End If
WaitForSingleObject(thread, INFINITE)
#endif
 
#ifdef __FB_LINUX__
' ... instructions only for Linux ...
#Include "crt/pthread.bi"
Function ThreadFunc As Any Ptr Cdecl Alias "ThreadFunc"(param As Any Ptr) Export
Print "Thread running"
Function = 0
End Function
Dim As pthread_t thread
If pthread_create(@thread, NULL, @ThreadFunc, NULL) <> 0 Then
Print "Error creating thread"
Sleep
End 1
End If
pthread_join(thread, NULL)
#endif
 
Print "Thread finished"
 
Sleep</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 828 ⟶ 980:
}
return res
}</langsyntaxhighlight>
{{out}}
<pre>
Line 837 ⟶ 989:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Parallel.Strategies (parMap, rdeepseq)
import Control.DeepSeq (NFData)
import Data.List (maximumBy)
import Data.Function (on)
 
nums :: [Integer]
nums = [112272537195293
[ 112272537195293
,112582718962171
, 112582718962171
,112272537095293
, 112272537095293
,115280098190773
, 115280098190773
,115797840077099
, 115797840077099
,1099726829285419]
, 1099726829285419
]
 
lowestFactor :: Integral a => a -> a -> a
:: Integral a
lowestFactor s n | n `rem` 2 == 0 = 2
=> a -> a -> a
| otherwise = head $ y
lowestFactor s n
where y = [x | x <- [s..ceiling . sqrt $ fromIntegral n]
| even n = 2
++ [n], n `rem` x == 0, x `rem` 2 /= 0]
| otherwise = head y
where
y =
[ x
| x <- [s .. ceiling . sqrt $ fromIntegral n] ++ [n]
, n `rem` x == 0
, odd x ]
 
primeFactors l n = f n l []
:: Integral a
where f n l xs = if n > 1 then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l:xs)
=> a -> a -> [a]
else xs
primeFactors l n = f n l []
where
f n l xs =
if n > 1
then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l : xs)
else xs
 
minPrimes
minPrimes ns = (\(x,y) -> (x,primeFactors y x)) $
:: (Control.DeepSeq.NFData a, Integral a)
maximumBy (compare `on` snd) $
=> [a] -> (a, [a])
zip ns (parMap rdeepseq (lowestFactor 3) ns)
minPrimes ns =
(\(x, y) -> (x, primeFactors y x)) $
maximumBy (compare `on` snd) $ zip ns (parMap rdeepseq (lowestFactor 3) ns)
 
main :: IO ()
main = print $ minPrimes nums</syntaxhighlight>
main = do
print $ minPrimes nums
</lang>
{{out}}
<pre>(115797840077099,[212609249,544651])</pre>
<pre>
(115797840077099,[212609249,544651])
</pre>
 
==Icon and {{header|Unicon}}==
Line 877 ⟶ 1,043:
The following only works in Unicon.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
threads := []
L := list(*A)
Line 894 ⟶ 1,060:
link factors
</syntaxhighlight>
</lang>
 
Sample run:
Line 904 ⟶ 1,070:
 
=={{header|J}}==
The code at [http://wwwcode.jsoftware.com/jwikiwiki/MarshallLochbaumUser:Marshall_Lochbaum/Parallelize] implements parallel computation. With it, we can write
<langsyntaxhighlight lang="j"> numbers =. 12757923 12878611 12878893 12757923 15808973 15780709 197622519
factors =. q:&.> parallelize 2 numbers NB. q: is parallelized here
ind =. (i. >./) <./@> factors
Line 911 ⟶ 1,077:
┌────────┬───────────┐
│12878611│47 101 2713│
└────────┴───────────┘</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import static java.lang.System.out;
 
import static java.util.Arrays.stream;
import static java.util.Comparator.comparing;
 
public interface ParallelCalculations {
public static final long[] NUMBERS = {
12757923,
12878611,
12878893,
12757923,
15808973,
15780709,
197622519
};
 
public static void main(String... arguments) {
stream(NUMBERS)
.unordered()
.parallel()
.mapToObj(ParallelCalculations::minimalPrimeFactor)
.max(comparing(a -> a[0]))
.ifPresent(res -> out.printf(
"%d has the largest minimum prime factor: %d%n",
res[1],
res[0]
));
;}
}
public static long[] minimalPrimeFactor(long n) {
 
public static long[] minimalPrimeFactor for (long i = 2; n >= i * i; i++) {
return iterate(2, i -> if (n % i +== 10) {
.filter(i -> n >= ireturn *new long[]{i), n};
.filter(i -> n % i == 0)}
}
.mapToObj(i -> new long[]{i, n})
return new long[]{n, n};
.findFirst()
}
.orElseGet(() -> new long[]{n, n})
}</syntaxhighlight>
;
}
}</lang>
 
<pre>12878611 has the largest minimum prime factor: 47</pre>
Line 962 ⟶ 1,125:
 
This first portion should be placed in a file called "parallel_worker.js". This file contains the logic used by every worker created.
<langsyntaxhighlight lang="javascript">
var onmessage = function(event) {
postMessage({"n" : event.data.n,
Line 979 ⟶ 1,142:
return factors;
}
</syntaxhighlight>
</lang>
 
For each number a worker is spawned. Once the final worker completes its task (worker_count is reduced to 0), the reduce function is called to determine which number is the answer.
<langsyntaxhighlight lang="javascript">
var numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519];
var workers = [];
Line 1,021 ⟶ 1,184:
console.log("The number with the relatively largest factors is: " + n + " : " + factors);
}
</syntaxhighlight>
</lang>
 
=={{header|MathematicaJulia}}==
<syntaxhighlight lang="julia">
<lang Mathematica>
using Primes
hasSmallestFactor[data_List]:=Sort[Transpose[{ParallelTable[FactorInteger[x][[1, 1]], {x, data}],data}]][[1, 2]]</lang>
 
factortodict(d, n) = (d[minimum(collect(keys(factor(n))))] = n)
 
# Numbers are from from the Raku example.
numbers = [64921987050997300559, 70251412046988563035, 71774104902986066597,
83448083465633593921, 84209429893632345702, 87001033462961102237,
87762379890959854011, 89538854889623608177, 98421229882942378967,
259826672618677756753, 262872058330672763871, 267440136898665274575,
278352769033314050117, 281398154745309057242, 292057004737291582187]
 
mins = Dict()
 
Base.@sync(
Threads.@threads for n in numbers
factortodict(mins, n)
end
)
 
answer = maximum(keys(mins))
println("The number that has the largest minimum prime factor is $(mins[answer]), with a smallest factor of $answer")
</syntaxhighlight>
{{out}}
<pre>
The number that has the largest minimum prime factor is 98421229882942378967, with a smallest factor of 736717
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.51
 
import java.util.stream.Collectors
 
/* returns the number itself, its smallest prime factor and all its prime factors */
fun primeFactorInfo(n: Int): Triple<Int, Int, List<Int>> {
if (n <= 1) throw IllegalArgumentException("Number must be more than one")
if (isPrime(n)) return Triple(n, n, listOf(n))
val factors = mutableListOf<Int>()
var factor = 2
var nn = n
while (true) {
if (nn % factor == 0) {
factors.add(factor)
nn /= factor
if (nn == 1) return Triple(n, factors.min()!!, factors)
if (isPrime(nn)) factor = nn
}
else if (factor >= 3) factor += 2
else factor = 3
}
}
 
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
 
fun main(args: Array<String>) {
val numbers = listOf(
12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519
)
val info = numbers.stream()
.parallel()
.map { primeFactorInfo(it) }
.collect(Collectors.toList())
val maxFactor = info.maxBy { it.second }!!.second
val results = info.filter { it.second == maxFactor }
println("The following number(s) have the largest minimal prime factor of $maxFactor:")
for (result in results) {
println(" ${result.first} whose prime factors are ${result.third}")
}
}</syntaxhighlight>
 
{{out}}
<pre>
The following number(s) have the largest minimal prime factor of 47:
12878611 whose prime factors are [47, 101, 2713]
12878893 whose prime factors are [47, 274019]
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">hasSmallestFactor[data_List]:=Sort[Transpose[{ParallelTable[FactorInteger[x][[1, 1]], {x, data}],data}]][[1, 2]]</syntaxhighlight>
 
=={{header|Nim}}==
===Using threads===
We use one thread per number to process. To find the lowest prime factor, we use a simple algorithm as performance is not important here.
 
Note that the program must be compiled with option <code>--threads:on</code>.
 
<syntaxhighlight lang="nim">import strformat, strutils, threadpool
 
const Numbers = [576460752303423487,
576460752303423487,
576460752303423487,
112272537195293,
115284584522153,
115280098190773,
115797840077099,
112582718962171,
299866111963290359]
 
 
proc lowestFactor(n: int64): int64 =
if n mod 2 == 0: return 2
if n mod 3 == 0: return 3
var p = 5
var delta = 2
while p * p < n:
if n mod p == 0: return p
inc p, delta
delta = 6 - delta
result = n
 
 
proc factors(n, lowest: int64): seq[int64] =
var n = n
var lowest = lowest
while true:
result.add lowest
n = n div lowest
if n == 1: break
lowest = lowestFactor(n)
 
 
# Launch a thread for each number to process.
var responses: array[Numbers.len, FlowVar[int64]]
for i, n in Numbers:
responses[i] = spawn lowestFactor(n)
 
# Read the results and find the largest minimum prime factor.
var maxMinfact = 0i64
var maxIdx: int
for i in 0..responses.high:
let minfact = ^responses[i] # Blocking read.
echo &"For n = {Numbers[i]}, the lowest factor is {minfact}."
if minfact > maxMinfact:
maxMinfact = minfact
maxIdx = i
let result = Numbers[maxIdx]
 
echo ""
echo "The first number with the largest minimum prime factor is: ", result
echo "Its factors are: ", result.factors(maxMinfact).join(", ")</syntaxhighlight>
 
{{out}}
<pre>For n = 576460752303423487, the lowest factor is 179951.
For n = 576460752303423487, the lowest factor is 179951.
For n = 576460752303423487, the lowest factor is 179951.
For n = 112272537195293, the lowest factor is 173.
For n = 115284584522153, the lowest factor is 513937.
For n = 115280098190773, the lowest factor is 513917.
For n = 115797840077099, the lowest factor is 544651.
For n = 112582718962171, the lowest factor is 3121.
For n = 299866111963290359, the lowest factor is 544651.
 
The first number with the largest minimum prime factor is: 115797840077099
Its factors are: 544651, 212609249</pre>
 
===Using parallel statement===
The parallel statement is an experimental feature. It uses threads but may simplify slightly the code in comparison to manual management.
Note that program must be compiled with option <code>--threads:on</code>.
 
<syntaxhighlight lang="nim">import sequtils, strutils, threadpool
 
{.experimental: "parallel".}
 
const Numbers = [576460752303423487,
576460752303423487,
576460752303423487,
112272537195293,
115284584522153,
115280098190773,
115797840077099,
112582718962171,
299866111963290359]
 
 
proc lowestFactor(n: int64): int64 =
if n mod 2 == 0: return 2
if n mod 3 == 0: return 3
var p = 5
var delta = 2
while p * p < n:
if n mod p == 0: return p
inc p, delta
delta = 6 - delta
result = n
 
 
proc factors(n, lowest: int64): seq[int64] =
var n = n
var lowest = lowest
while true:
result.add lowest
n = n div lowest
if n == 1: break
lowest = lowestFactor(n)
 
 
# Launch the threads.
var results: array[Numbers.len, int64] # To store the results.
parallel:
for i, n in Numbers:
results[i] = spawn lowestFactor(n)
 
# Find the minimum prime factor and the first number with this minimum factor.
let maxIdx = results.maxIndex()
let maxMinfact = results[maxIdx]
let result = Numbers[maxIdx]
 
echo ""
echo "The first number with the largest minimum prime factor is: ", result
echo "Its factors are: ", result.factors(maxMinfact).join(", ")</syntaxhighlight>
 
{{out}}
Output is the same as with manual management of threads.
 
=={{header|Oforth}}==
Line 1,037 ⟶ 1,423:
Numbers of workers to use can be adjusted using --W command line option.
 
<langsyntaxhighlight Oforthlang="oforth">import: parallel
 
: largeMinFactor dup mapParallel(#factors) zip maxFor(#[ second first ]) ; </langsyntaxhighlight>
 
{{out}}
Line 1,047 ⟶ 1,433:
</pre>
 
=={{header|PARI/GPooRexx}}==
This program calls the programs shown under REXX (modified for ooRexx and slightly expanded).
See [http://pari.math.u-bordeaux1.fr/Events/PARI2012/talks/pareval.pdf Bill Allombert's slides on parallel programming in GP]. This can be configured to use either MPI (good for many networked computers) or pthreads (good for a single machine).
<syntaxhighlight lang="oorexx">/* Concurrency in ooRexx. Example of early reply */
{{works with|PARI/GP|2.6 with bill-pareval branch}}
object1 = .example~new
<lang parigp>v=pareval(vector(1000,i,()->factor(2^i+1)[1,1]));
object2 = .example~new
vecmin(v)</lang>
say object1~primes(1,11111111111,11111111114)
say object2~primes(2,11111111111,11111111114)
say "Main ended at" time()
exit
::class example
::method primes
use arg which,bot,top
reply "Start primes"which':' time()
Select
When which=1 Then Call pd1 bot top
When which=2 Then Call pd2 bot top
End </syntaxhighlight>
{{out}}
<pre>Start primes1: 09:25:25
Start primes2: 09:25:25
11111111111 (2) prime factors: 21649 513239
Main ended at 09:25:25
11111111112 (5) prime factors: 2 2 2 3 462962963
11111111111 (2) prime factors: 21649 513239
11111111112 (5) prime factors: 2 2 2 3 462962963
11111111113 (1) prime factors: [prime] 11111111113
11111111113 (1) prime factors: [prime] 11111111113
11111111114 (2) prime factors: 2 5555555557
 
1 primes found.
PD1 took 1.203000 seconds
11111111114 (2) prime factors: 2 5555555557
 
1 primes found.
PD2 took 1.109000 seconds</pre>
<syntaxhighlight lang="rexx">
/*PD1 REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/
Call Time 'R'
numeric digits 1000 /*handle thousand digits for the powers*/
parse arg bot top step base add /*get optional arguments from the C.L. */
if bot=='' then do; bot=1; top=100; end /*no BOT given? Then use the default.*/
if top=='' then top=bot /* " TOP? " " " " " */
if step=='' then step= 1 /* " STEP? " " " " " */
if add =='' then add= -1 /* " ADD? " " " " " */
tell= top>0; top=abs(top) /*if TOP is negative, suppress displays*/
w=length(top) /*get maximum width for aligned display*/
if base\=='' then w=length(base**top) /*will be testing powers of two later? */
commat.=left('', 7); commat.0="{unity}"; commat.1='[prime]' /*some literals: pad; prime (or not).*/
numeric digits max(9, w+1) /*maybe increase the digits precision. */
hash=0 /*hash: is the number of primes found. */
do n=bot to top by step /*process a single number or a range.*/
?=n; if base\=='' then ?=base**n + add /*should we perform a "Mercenne" test? */
pf=factr(?); f=words(pf) /*get prime factors; number of factors.*/
if f==1 then hash=hash+1 /*Is N prime? Then bump prime counter.*/
if tell then say right(?,w) right('('f")",9) 'prime factors: ' commat.f pf
end /*n*/
say
ps= 'primes'; if p==1 then ps= "prime" /*setup for proper English in sentence.*/
say right(hash, w+9+1) ps 'found.' /*display the number of primes found. */
Say 'PD1 took' time('E') 'seconds'
exit /*stick a fork in it, we're all done. */
/*--------------------------------------------------------------------------------------*/
factr: procedure; parse arg x 1 d,dollar /*set X, D to argument 1; dollar to null.*/
if x==1 then return '' /*handle the special case of X = 1. */
do while x//2==0; dollar=dollar 2; x=x%2; end /*append all the 2 factors of new X.*/
do while x//3==0; dollar=dollar 3; x=x%3; end /* " " " 3 " " " " */
do while x//5==0; dollar=dollar 5; x=x%5; end /* " " " 5 " " " " */
do while x//7==0; dollar=dollar 7; x=x%7; end /* " " " 7 " " " " */
/* ___*/
q=1; do while q<=x; q=q*4; end /*these two lines compute integer v X */
r=0; do while q>1; q=q%4; _=d-r-q; r=r%2; if _>=0 then do; d=_; r=r+q; end; end
 
do j=11 by 6 to r /*insure that J isn't divisible by 3.*/
parse var j '' -1 _ /*obtain the last decimal digit of J. */
if _\==5 then do while x//j==0; dollar=dollar j; x=x%j; end /*maybe reduce by J. */
if _ ==3 then iterate /*Is next Y is divisible by 5? Skip.*/
y=j+2; do while x//y==0; dollar=dollar y; x=x%y; end /*maybe reduce by J. */
end /*j*/
/* [?] The dollar list has a leading blank.*/
if x==1 then return dollar /*Is residual=unity? Then don't append.*/
return dollar x /*return dollar with appended residual. */</syntaxhighlight>
<syntaxhighlight lang="rexx">/*PD2 REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/
Call time 'R'
numeric digits 1000 /*handle thousand digits for the powers*/
parse arg bot top step base add /*get optional arguments from the C.L. */
if bot=='' then do; bot=1; top=100; end /*no BOT given? Then use the default.*/
if top=='' then top=bot /* " TOP? " " " " " */
if step=='' then step= 1 /* " STEP? " " " " " */
if add =='' then add= -1 /* " ADD? " " " " " */
tell= top>0; top=abs(top) /*if TOP is negative, suppress displays*/
w=length(top) /*get maximum width for aligned display*/
if base\=='' then w=length(base**top) /*will be testing powers of two later? */
commat.=left('', 7); commat.0="{unity}"; commat.1='[prime]' /*some literals: pad; prime (or not).*/
numeric digits max(9, w+1) /*maybe increase the digits precision. */
hash=0 /*hash: is the number of primes found. */
do n=bot to top by step /*process a single number or a range.*/
?=n; if base\=='' then ?=base**n + add /*should we perform a "Mercenne" test? */
pf=factr(?); f=words(pf) /*get prime factors; number of factors.*/
if f==1 then hash=hash+1 /*Is N prime? Then bump prime counter.*/
if tell then say right(?,w) right('('f")",9) 'prime factors: ' commat.f pf
end /*n*/
say
ps= 'primes'; if p==1 then ps= "prime" /*setup for proper English in sentence.*/
say right(hash, w+9+1) ps 'found.' /*display the number of primes found. */
Say 'PD2 took' time('E') 'seconds'
exit /*stick a fork in it, we're all done. */
/*--------------------------------------------------------------------------------------*/
factr: procedure; parse arg x 1 d,dollar /*set X, D to argument 1; dollar to null.*/
if x==1 then return '' /*handle the special case of X = 1. */
do while x// 2==0; dollar=dollar 2; x=x%2; end /*append all the 2 factors of new X.*/
do while x// 3==0; dollar=dollar 3; x=x%3; end /* " " " 3 " " " " */
do while x// 5==0; dollar=dollar 5; x=x%5; end /* " " " 5 " " " " */
do while x// 7==0; dollar=dollar 7; x=x%7; end /* " " " 7 " " " " */
do while x//11==0; dollar=dollar 11; x=x%11; end /* " " " 11 " " " " */ /* ?¦¦¦¦ added.*/
do while x//13==0; dollar=dollar 13; x=x%13; end /* " " " 13 " " " " */ /* ?¦¦¦¦ added.*/
do while x//17==0; dollar=dollar 17; x=x%17; end /* " " " 17 " " " " */ /* ?¦¦¦¦ added.*/
do while x//19==0; dollar=dollar 19; x=x%19; end /* " " " 19 " " " " */ /* ?¦¦¦¦ added.*/
do while x//23==0; dollar=dollar 23; x=x%23; end /* " " " 23 " " " " */ /* ?¦¦¦¦ added.*/
/* ___*/
q=1; do while q<=x; q=q*4; end /*these two lines compute integer v X */
r=0; do while q>1; q=q%4; _=d-r-q; r=r%2; if _>=0 then do; d=_; r=r+q; end; end
 
do j=29 by 6 to r /*insure that J isn't divisible by 3.*/ /* ?¦¦¦¦ changed.*/
parse var j '' -1 _ /*obtain the last decimal digit of J. */
if _\==5 then do while x//j==0; dollar=dollar j; x=x%j; end /*maybe reduce by J. */
if _ ==3 then iterate /*Is next Y is divisible by 5? Skip.*/
y=j+2; do while x//y==0; dollar=dollar y; x=x%y; end /*maybe reduce by J. */
end /*j*/
/* [?] The dollar list has a leading blank.*/
if x==1 then return dollar /*Is residual=unity? Then don't append.*/
return dollar x /*return dollar with appended residual. */</syntaxhighlight>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
'CONFIGURATION
'=============
Line 1,236 ⟶ 1,748:
 
print str((t2-t1)/freq,3) " secs " numbers(n) " " f 'number with highest prime factor
</syntaxhighlight>
</lang>
 
=={{header|Perl 6PARI/GP}}==
See [http://pari.math.u-bordeaux1.fr/Events/PARI2012/talks/pareval.pdf Bill Allombert's slides on parallel programming in GP]. This can be configured to use either MPI (good for many networked computers) or pthreads (good for a single machine).
Assuming that <tt>factors</tt> is defined exactly as in the prime decomposition task:
{{works with|PARI/GP|2.6.2+}}
<lang perl6>my @nums = 12757923, 12878611, 123456789, 15808973, 15780709, 197622519;
<syntaxhighlight lang="parigp">v=pareval(vector(1000,i,()->factor(2^i+1)[1,1]));
vecmin(v)</syntaxhighlight>
 
=={{header|Perl}}==
my @factories;
{{libheader|ntheory}}
@factories[$_] := factors(@nums[$_]) for ^@nums;
<syntaxhighlight lang="perl">use ntheory qw/factor vecmax/;
my $gmf = ([max] @factories»[0] »=>« @nums).value;
use threads;
</lang>
use threads::shared;
The line with the <tt>for</tt> loop is just setting up a bunch of lazy lists, one for each number to be factored, but doesn't actually do any of the work of factoring.
my @results :shared;
Most of the parallelizing work is done by the hyperoperators that demand the first value from each of the factories' lists, then builds (again in parallel) the pairs associating each first value with its original value. The <tt>[max]</tt> reduction finds the pair with the largest key, from which we can easily extract the greatest minimum factor candidate, and then refactor it completely.
 
my $tnum = 0;
The [[rakudo]] system does not actually do hypers in parallel yet, but when it does, this can automatically parallelize. (Hypers do parallelize in [[pugs]], but it doesn't do some of the other things we rely on here.) It will be up to each individual compiler to determine how many cores to use for any given hyperoperator; the construct merely promises the compiler that it can be parallelized, but does not require that it must be.
$_->join() for
map { threads->create('tfactor', $tnum++, $_) }
(qw/576460752303423487 576460752303423487 576460752303423487 112272537195293
115284584522153 115280098190773 115797840077099 112582718962171 299866111963290359/);
 
my $lmf = vecmax( map { $_->[1] } @results );
There is also some pipelining that can happen within the <tt>factors</tt> routine itself, which uses a <tt>gather</tt>/<tt>take</tt> construct, which the compiler may implement using either coroutines or threads as it sees fit.
print "Largest minimal factor of $lmf found in:\n";
Threading pipelines can make more sense on, say, a cell architecture.
print " $_->[0] = [@$_[1..$#$_]]\n" for grep { $_->[1] == $lmf } @results;
 
sub tfactor {
my($tnum, $n) = @_;
push @results, shared_clone([$n, factor($n)]);
}</syntaxhighlight>
{{out}}
<pre>
Largest minimal factor of 544651 found in:
115797840077099 = [544651 212609249]
299866111963290359 = [544651 550565613509]
</pre>
 
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\ParallelCalculations.exw
-- =====================================
--
-- Proof that more threads can make things faster...
--</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (threads)</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">res_cs</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">init_cs</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- critical section</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">athread</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #7060A8;">enter_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">leave_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">found</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">found</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_prime_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1_000_000</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">enter_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">found</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #7060A8;">leave_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">exit_thread</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">nthreads</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">progress</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"testing %d threads..."</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">nthreads</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">threads</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">nthreads</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">threads</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">threads</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">create_thread</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"athread"</span><span style="color: #0000FF;">),{}))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">wait_thread</span><span style="color: #0000FF;">(</span><span style="color: #000000;">threads</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">largest</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"largest is 2^%d+1 with smallest factor of %d (%d threads, %s)\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">nthreads</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">delete_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
largest is 2^64+1 with smallest factor of 274177 (1 threads, 9.5s)
largest is 2^64+1 with smallest factor of 274177 (2 threads, 7.1s)
largest is 2^64+1 with smallest factor of 274177 (3 threads, 5.8s)
largest is 2^64+1 with smallest factor of 274177 (4 threads, 4.5s)
largest is 2^64+1 with smallest factor of 274177 (5 threads, 4.5s)
</pre>
IE: Checking the first 1 million primes as factors of 2^(1..100)+1 takes 1 core 9.5s and less when spread over multiple cores.<br>
Note however that I added quite a bit of locking to mpz_prime_factors(), specifically around get_prime() and mpz_probable_prime(),
[happy to leave it in since the effect on the single-thread case was neglible] so it is really only the mpz_divisible_ui_p() calls
and some control-flow scaffolding that is getting parallelised. I only got 4 cores so the 5th thread was not expected to help.
 
=={{header|PicoLisp}}==
Line 1,260 ⟶ 1,859:
'[http://software-lab.de/doc/refW.html#wait wait]'s until all results are
available:
<langsyntaxhighlight PicoLisplang="picolisp">(let Lst
(mapcan
'((N)
Line 1,279 ⟶ 1,878:
122811709478644363796375689 ) )
(wait NIL (full Lst)) # Wait until all computations are done
(maxi '((L) (apply min L)) Lst) ) # Result: Number in CAR, factors in CDR</langsyntaxhighlight>
{{out}}
<pre>-> (2532817738450130259664889 6531761 146889539 2639871491)</pre>
Line 1,290 ⟶ 1,889:
This piece needs prime_decomp definition from the [[Prime decomposition#Prolog]] example, it worked on my swipl, but I don't know how other Dialects thread.
 
<langsyntaxhighlight Prologlang="prolog">threaded_decomp(Number,ID):-
thread_create(
(prime_decomp(Number,Y),
Line 1,321 ⟶ 1,920:
format('Number with largest minimal Factor is ~w\nFactors are ~w\n',
[Number,Factors]).
</syntaxhighlight>
</lang>
 
Example (Numbers Same as in Ada Example):
Line 1,338 ⟶ 1,937:
true.
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Structure IO_block
ThreadID.i
StartSeamaphore.i
Line 1,426 ⟶ 2,026:
end_of_data:
EndDataSection
</syntaxhighlight>
</lang>
[[image:PB_Parallel_Calculations.png]]
 
Line 1,434 ⟶ 2,034:
 
<small>Note that there is no need to calculate all prime factors of all <code>NUMBERS</code> when only the prime factors of the number with the lowest overall prime factor is needed.</small>
<langsyntaxhighlight lang="python">from concurrent import futures
from math import floor, sqrt
Line 1,478 ⟶ 2,078:
if __name__ == '__main__':
main()</langsyntaxhighlight>
 
{{out}}
Line 1,496 ⟶ 2,096:
<p>This method works for both Python2 and Python3 using the standard library module [https://docs.python.org/3/library/multiprocessing.html multiprocessing]. The result of the following code is the same as the previous example only the different package is used. </p>
 
<langsyntaxhighlight lang="python">import multiprocessing
 
# ========== #Python3 - concurrent
Line 1,542 ⟶ 2,142:
print(' The one with the largest minimum prime factor is {}:'.format(number))
print(' All its prime factors in order are: {}'.format(all_factors))
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 1,571 ⟶ 2,171:
; get the results and find the maximum:
(argmax first (map place-channel-get ps)))
</syntaxhighlight>
</lang>
Session:
<langsyntaxhighlight lang="racket">
> (main)
'(544651 115797840077099)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Takes the list of numbers and converts them to a <tt>HyperSeq</tt> that is stored in a variable and evaluated concurrently. <tt>HyperSeq</tt>s overload <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>HyperSeq</tt> is lazy, so the computation of values will happen in chunks as they are requested.
 
The hyper (and race) method can take two parameters that will tweak how the parallelization occurs: :degree and :batch. :degree is the number of worker threads to allocate to the job. By default it is set to the number of physical cores available. If you have a hyper threading processor, and the tasks are not cpu bound, it may be useful to raise that number but it is a reasonable default. :batch is how many sub-tasks are parceled out at a time to each worker thread. Default is 64. For small numbers of cpu intensive tasks a lower number will likely be better, but too low may make the dispatch overhead cancel out the benefit of threading. Conversely, too high will over-burden some threads and starve others. Over long-running processes with many hundreds / thousands of sub-tasks, the scheduler will automatically adjust the batch size up or down to try to keep the pipeline filled.
 
On my system, under the load I was running, I found a batch size of 3 to be optimal for this task. May be different for different systems and different loads.
 
As a relative comparison, perform the same factoring task on the same set of 100 numbers as found in the [[Parallel_calculations#SequenceL|SequenceL]] example, using varying numbers of threads. The absolute speed numbers are not very significant, they will vary greatly between systems, this is more intended as a comparison of relative throughput. On a Core i7-4770 @ 3.40GHz with 4 cores and hyper-threading under Linux, there is a distinct pattern where more threads on physical cores give reliable increases in throughput. Adding hyperthreads may (and, in this case, does seem to) give some additional marginal benefit.
 
Using the <tt>prime-factors</tt> routine as defined in the [[Prime_decomposition#Raku|prime decomposition]] task.
<syntaxhighlight lang="raku" line>my @nums = 64921987050997300559, 70251412046988563035, 71774104902986066597,
83448083465633593921, 84209429893632345702, 87001033462961102237,
87762379890959854011, 89538854889623608177, 98421229882942378967,
259826672618677756753, 262872058330672763871, 267440136898665274575,
278352769033314050117, 281398154745309057242, 292057004737291582187;
 
my @factories = @nums.hyper(:3batch).map: &prime-factors;
printf "%21d factors: %s\n", |$_ for @nums Z @factories;
my $gmf = {}.append(@factories»[0] »=>« @nums).max: +*.key;
say "\nGreatest minimum factor: ", $gmf.key;
say "from: { $gmf.value }\n";
say 'Run time: ', now - INIT now;
say '-' x 80;
 
# For amusements sake and for relative comparison, using the same 100
# numbers as in the SequenceL example, testing with different numbers of threads.
 
@nums = <625070029 413238785 815577134 738415913 400125878 967798656 830022841
774153795 114250661 259366941 571026384 522503284 757673286 509866901 6303092
516535622 177377611 520078930 996973832 148686385 33604768 384564659 95268916
659700539 149740384 320999438 822361007 701572051 897604940 2091927 206462079
290027015 307100080 904465970 689995756 203175746 802376955 220768968 433644101
892007533 244830058 36338487 870509730 350043612 282189614 262732002 66723331
908238109 635738243 335338769 461336039 225527523 256718333 277834108 430753136
151142121 602303689 847642943 538451532 683561566 724473614 422235315 921779758
766603317 364366380 60185500 333804616 988528614 933855820 168694202 219881490
703969452 308390898 567869022 719881996 577182004 462330772 770409840 203075270
666478446 351859802 660783778 503851023 789751915 224633442 347265052 782142901
43731988 246754498 736887493 875621732 594506110 854991694 829661614 377470268
984990763 275192380 39848200 892766084 76503760>».Int;
 
for 1..8 -> $degree {
my $start = now;
my \factories = @nums.hyper(:degree($degree), :3batch).map: &prime-factors;
my $gmf = {}.append(factories»[0] »=>« @nums).max: +*.key;
say "\nFactoring {+@nums} numbers, greatest minimum factor: {$gmf.key}";
say "Using: $degree thread{ $degree > 1 ?? 's' !! ''}";
my $end = now;
say 'Run time: ', $end - $start, ' seconds.';
}
 
# Prime factoring routines from the Prime decomposition task
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 ) {
return 2 unless $n +& 1;
if (my $gcd = $n gcd 6541380665835015) > 1 {
return $gcd if $gcd != $n
}
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;
}</syntaxhighlight>
{{out|Typical output}}
<pre> 64921987050997300559 factors: 736717 88123373087627
70251412046988563035 factors: 5 43 349 936248577956801
71774104902986066597 factors: 736717 97424255043641
83448083465633593921 factors: 736717 113270202079813
84209429893632345702 factors: 2 3 3 3 41 107880821 352564733
87001033462961102237 factors: 736717 118092881612561
87762379890959854011 factors: 3 3 3 3 331 3273372119315201
89538854889623608177 factors: 736717 121537652707381
98421229882942378967 factors: 736717 133594351539251
259826672618677756753 factors: 7 37118096088382536679
262872058330672763871 factors: 3 47 1864340839224629531
267440136898665274575 factors: 3 5 5 71 50223499887073291
278352769033314050117 factors: 7 39764681290473435731
281398154745309057242 factors: 2 809 28571 46061 132155099
292057004737291582187 factors: 7 151 373 2339 111323 2844911
 
Greatest minimum factor: 736717
from: 64921987050997300559 71774104902986066597 83448083465633593921 87001033462961102237 89538854889623608177 98421229882942378967
 
Run time: 0.2968644
--------------------------------------------------------------------------------
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 1 thread
Run time: 0.3438752 seconds.
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 2 threads
Run time: 0.2035372 seconds.
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 3 threads
Run time: 0.14177834 seconds.
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 4 threads
Run time: 0.110738 seconds.
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 5 threads
Run time: 0.10142434 seconds.
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 6 threads
Run time: 0.10954304 seconds.
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 7 threads
Run time: 0.097886 seconds.
 
Factoring 100 numbers, greatest minimum factor: 782142901
Using: 8 threads
Run time: 0.0927695 seconds.</pre>
 
Beside <tt>HyperSeq</tt> and its (allowed to be) out-of-order equivalent <tt>RaceSeq</tt>, [[Rakudo]] supports primitive threads, locks and highlevel promises. Using channels and supplies values can be move thread-safely from one thread to another. A react-block can be used as a central hub for message passing.
 
In [[Raku]] most errors are bottled up <tt>Exceptions</tt> inside <tt>Failure</tt> objects that remember where they are created and thrown when used. This is useful to pass errors from one thread to another without losing file and line number of the source file that caused the error.
 
In the future hyper operators, junctions and feeds will be candidates for autothreading.
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
//! This solution uses [rayon](https://github.com/rayon-rs/rayon), a data-parallelism library.
//! Since Rust guarantees that a program has no data races, adding parallelism to a sequential
//! computation is as easy as importing the rayon traits and calling the `par_iter()` method.
 
extern crate rayon;
 
extern crate prime_decomposition;
 
use rayon::prelude::*;
 
/// Returns the largest minimal factor of the numbers in a slice
pub fn largest_min_factor(numbers: &[usize]) -> usize {
numbers
.par_iter()
.map(|n| {
// `factor` returns a sorted vector, so we just take the first element.
prime_decomposition::factor(*n)[0]
})
.max()
.unwrap()
}
 
fn main() {
let numbers = &[
1_122_725, 1_125_827, 1_122_725, 1_152_800, 1_157_978, 1_099_726,
];
let max = largest_min_factor(numbers);
println!("The largest minimal factor is {}", max);
}
</syntaxhighlight>
{{out}}
<pre>
The largest minimal factor is 23
</pre>
 
=={{header|SequenceL}}==
SequenceL compiles to parallel C++ without any input from the user regarding explicit parallelization. The number of threads to be executed on can be specified at runtime, or by default, the runtime detects the maximum number of logical cores and uses that many threads.
 
<langsyntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>;
import <Utilities/Math.sl>;
import <Utilities/Sequence.sl>;
Line 1,594 ⟶ 2,372:
indexOfMax := firstIndexOf(minFactors, vectorMax(minFactors));
in
"Number " ++ intToString(inputs[indexOfMax]) ++ " has largest minimal factor:\n" ++ delimit(intToString(factored[indexOfMax]), ' ');</langsyntaxhighlight>
 
Using the Trial Division version of primeFactorization here: [http://rosettacode.org/wiki/Prime_decomposition#SequenceL]
 
The primary source of parallelization in the above code is from the line:
<langsyntaxhighlight lang="sequencel">factored := primeFactorization(inputs);</langsyntaxhighlight>
Since primeFactorization is defined on scalar integers and inputs is a sequence of integers, this call results in a Normalize Transpose. The value of factored will be the sequence of results of applying primeFactorization to each element of inputs.
 
Line 1,642 ⟶ 2,420:
=={{header|Sidef}}==
The code uses the ''prime_factors()'' function defined in the "Prime decomposition" task.
<langsyntaxhighlight lang="ruby">var nums = [1275792312878611, 12345678915808973,
1578070919762253, 14700694496703910,];
 
var factors = nums.map {|n| prime_factors.ffork(n) }.map { .wait }
say ((nums ~Z factors)->max_by {|m| m[1][0] })</langsyntaxhighlight>
{{out}}
<pre>
Line 1,653 ⟶ 2,431:
sidef parallel.sf 24.46s user 0.02s system 158% cpu 15.436 total
</pre>
 
=={{header|Standard ML}}==
Parallel code is from the 'concurrent computing task'. Works with PolyML. Function -factor- is a deformatted version of the one from the prime decomposition page.
<syntaxhighlight lang="standard ml">
structure TTd = Thread.Thread ;
structure TTm = Thread.Mutex ;
 
 
val threadedBigPrime = fn input:IntInf.int list =>
 
let
 
(* --------------------- code from prime decomposition page ------------------- *)
val factor = fn n :IntInf.int =>
let
val unfactored = fn (u,_,_) => u; val factors = fn (_,f,_) => f; val try = fn (_,_,i) => i; fun getresult t = unfactored t::(factors t);
fun until done change x = if done x then getresult x else until done change (change x); (* iteration *)
fun lastprime t = unfactored t < (try t)*(try t)
fun trymore t = if unfactored t mod (try t) = 0 then (unfactored t div (try t) , try t::(factors t) , try t) else (unfactored t, factors t , try t + 1)
in until lastprime trymore (n,[],2) end;
(* --------------------- end of code from prime decomposition page ------------ *)
 
 
val mx = TTm.mutex () ;
val results : IntInf.int list list ref = ref [ ] ;
val tasks : IntInf.int list list ref = ref [ ] ;
 
 
val divideup = fn cores => fn inp : IntInf.int list =>
let
val np = (List.length inp) div cores + (cores +1) div cores (* assume length > cores to reduce code *)
val rec divd = fn ([], outp) => ([],outp )
| (inp,outp) => divd ( List.drop (inp,np) , (List.take (inp,np))::outp ) handle Subscript => ([],inp :: outp)
in
#2 ( divd (inp, [ ] ))
end;
 
val doTask = fn () =>
let
val mytask : IntInf.int list ref = ref [];
val myres : IntInf.int list list ref = ref [];
in
( TTm.lock mx ; mytask := hd ( !tasks ) ; tasks:= tl (!tasks) ; TTm.unlock mx ;
myres := List.map factor ( !mytask ) ;
TTm.lock mx ; results := !myres @ ( !results ) ; TTm.unlock mx ;
TTd.exit ()
)
end;
 
 
val cores = TTd.numProcessors ();
val tmp = tasks := divideup cores input ;
val processes = List.tabulate ( cores , fn i => TTd.fork (doTask , []) ) ;
val maxim = ( while ( List.exists TTd.isActive processes ) do (Posix.Process.sleep (Time.fromReal 1.0 ));
List.foldr IntInf.max 1 ( List.map (fn i => List.last i ) (!results) ) ) (* maximal lowest prime *)
 
in
 
List.filter (fn lst => List.last lst = maxim ) (!results)
 
end ;
</syntaxhighlight>
call and output - interpreter
<syntaxhighlight lang="standard ml">
> threadedBigPrime [ 62478923478923409323, 69478923478923409313, 79234790234098402349,
33498023480920234793, 92834098234098023409, 31908234098234098243,
92873400002348028833, 73498200234098200239, 4349023423478999243,
13480234982340982343, 62478923478925971503, 5340823480234982007,
134802349691098498233, 81780923490092302251, 802487292348792949 ] ;
 
val it = [[1463103844669601, 42703], [1463103844669541, 42703]]:
 
(* numbers *)
> List.map (List.foldr IntInf.* 1 ) it ;
val it = [62478923478925971503, 62478923478923409323]: IntInf.int list
</syntaxhighlight>
 
=={{header|Swift}}==
 
{{libheader|AttaSwift BigInt}}
 
<syntaxhighlight lang="swift">import BigInt
import Foundation
 
extension BinaryInteger {
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
 
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
 
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
var q: Self = self & 1 == 0 ? 2 : 3
 
while q <= maxQ && self % q != 0 {
q = step(d)
d += 1
}
 
return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self]
}
}
 
let numbers = [
112272537195293,
112582718962171,
112272537095293,
115280098190773,
115797840077099,
1099726829285419,
1275792312878611,
BigInt("64921987050997300559")
]
 
func findLargestMinFactor<T: BinaryInteger>(for nums: [T], then: @escaping ((n: T, factors: [T])) -> ()) {
let waiter = DispatchSemaphore(value: 0)
let lock = DispatchSemaphore(value: 1)
var factors = [(n: T, factors: [T])]()
 
DispatchQueue.concurrentPerform(iterations: nums.count) {i in
let n = nums[i]
 
print("Factoring \(n)")
 
let nFacs = n.primeDecomposition().sorted()
 
print("Factored \(n)")
 
lock.wait()
factors.append((n, nFacs))
 
if factors.count == nums.count {
waiter.signal()
}
 
lock.signal()
}
 
waiter.wait()
 
then(factors.sorted(by: { $0.factors.first! > $1.factors.first! }).first!)
}
 
findLargestMinFactor(for: numbers) {res in
let (n, factors) = res
 
print("Number with largest min prime factor: \(n); factors: \(factors)")
 
exit(0)
}
 
dispatchMain()</syntaxhighlight>
 
{{out}}
 
<pre>$ time ./.build/x86_64-apple-macosx/release/Runner
Factoring 112272537195293
Factoring 64921987050997300559
Factoring 112582718962171
Factoring 112272537095293
Factoring 115797840077099
Factoring 115280098190773
Factoring 1099726829285419
Factoring 1275792312878611
Factored 1099726829285419
Factored 112582718962171
Factored 112272537095293
Factored 1275792312878611
Factored 112272537195293
Factored 115280098190773
Factored 115797840077099
Factored 64921987050997300559
Number with largest min prime factor: 64921987050997300559; factors: [736717, 88123373087627]
 
real 0m2.983s
user 0m3.570s
sys 0m0.012s</pre>
 
=={{header|Tcl}}==
With Tcl, it is necessary to explicitly perform computations in other threads because each thread is strongly isolated from the others (except for inter-thread messaging). However, it is entirely practical to wrap up the communications so that only a small part of the code needs to know very much about it, and in fact most of the complexity is managed by a thread pool; each value to process becomes a work item to be handled. It is easier to transfer the results by direct messaging instead of collecting the thread pool results, since we can leverage Tcl's <code>vwait</code> command nicely.
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
package require Thread
 
Line 1,698 ⟶ 2,657:
return [array get result]
}
}</langsyntaxhighlight>
This is the definition of the prime factorization engine (a somewhat stripped-down version of the [[Prime decomposition#Tcl|Tcl Prime decomposition solution]]:
<langsyntaxhighlight lang="tcl"># Code for computing the prime factors of a number
set computationCode {
namespace eval prime {
Line 1,766 ⟶ 2,725:
2532817738450130259664889
122811709478644363796375689
}</langsyntaxhighlight>
Putting everything together:
<langsyntaxhighlight lang="tcl"># Do the computation, getting back a dictionary that maps
# values to its results (itself an ordered dictionary)
set results [pooled::computation $computationCode prime::factors $values]
Line 1,782 ⟶ 2,741:
return [join $v "*"]
}
puts "$best = [renderFactors [dict get $results $best]]"</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
{{libheader|OpenMP}}
{{libheader|Wren-math}}
<br>
Although all Wren code runs within the context of a fiber (of which there can be thousands) only one fiber can run at a time and so the language's virtual machine (VM) is effectively single threaded.
 
However, it's possible for a suitable host on a suitable machine to run multiple VMs in parallel as the following example, with a C host, shows when run on a machine with four cores. Four VMs are used each of which runs on its own thread.
<syntaxhighlight lang="wren">/* Parallel_calculations.wren */
 
import "./math" for Int
 
class C {
static minPrimeFactor(n) { Int.primeFactors(n)[0] }
 
static allPrimeFactors(n) { Int.primeFactors(n) }
}</syntaxhighlight>
<br>
We now embed this Wren script in the following C program, compile and run it.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include "wren.h"
 
#define NUM_VMS 4
 
WrenVM* vms[NUM_VMS]; // array of VMs
 
void doParallelCalcs() {
int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519};
int i, count, largest, largest_factor = 0;
omp_set_num_threads(4);
// we can share the same call and class handles amongst VMs
WrenHandle* callHandle = wrenMakeCallHandle(vms[0], "minPrimeFactor(_)");
WrenHandle* callHandle2 = wrenMakeCallHandle(vms[0], "allPrimeFactors(_)");
wrenEnsureSlots(vms[0], 1);
wrenGetVariable(vms[0], "main", "C", 0);
WrenHandle* classHandle = wrenGetSlotHandle(vms[0], 0);
 
#pragma omp parallel for shared(largest_factor, largest)
for (i = 0; i < 7; ++i) {
int n = data[i];
int vi = omp_get_thread_num(); // assign a VM (via its array index) for this number
wrenEnsureSlots(vms[vi], 2);
wrenSetSlotHandle(vms[vi], 0, classHandle);
wrenSetSlotDouble(vms[vi], 1, (double)n);
wrenCall(vms[vi], callHandle);
int p = (int)wrenGetSlotDouble(vms[vi], 0);
if (p > largest_factor) {
largest_factor = p;
largest = n;
printf("Thread %d: found larger: %d of %d\n", vi, p, n);
} else {
printf("Thread %d: not larger: %d of %d\n", vi, p, n);
}
}
 
printf("\nLargest minimal prime factor: %d of %d\n", largest_factor, largest);
printf("All prime factors for this number: ");
wrenEnsureSlots(vms[0], 2);
wrenSetSlotHandle(vms[0], 0, classHandle);
wrenSetSlotDouble(vms[0], 1, (double)largest);
wrenCall(vms[0], callHandle2);
count = wrenGetListCount(vms[0], 0);
for (i = 0; i < count; ++i) {
wrenGetListElement(vms[0], 0, i, 1);
printf("%d ", (int)wrenGetSlotDouble(vms[0], 1));
}
printf("\n");
wrenReleaseHandle(vms[0], callHandle);
wrenReleaseHandle(vms[0], callHandle2);
wrenReleaseHandle(vms[0], classHandle);
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
 
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.loadModuleFn = &loadModule;
const char* module = "main";
const char* fileName = "Parallel_calculations.wren";
char *script = readFile(fileName);
 
// config the VMs and interpret the script
int i;
for (i = 0; i < NUM_VMS; ++i) {
vms[i] = wrenNewVM(&config);
wrenInterpret(vms[i], module, script);
}
doParallelCalcs();
for (i = 0; i < NUM_VMS; ++i) wrenFreeVM(vms[i]);
free(script);
return 0;
}</syntaxhighlight>
{{out}}
Sample output as this will obviously vary depending on which threads return first and which of the two numbers with a minimal prime factor of 47 is found first.
<pre>
Thread 0: found larger: 3 of 12757923
Thread 2: found larger: 29 of 15808973
Thread 0: found larger: 47 of 12878611
Thread 2: not larger: 7 of 15780709
Thread 1: not larger: 47 of 12878893
Thread 1: not larger: 3 of 12757923
Thread 3: not larger: 3 of 197622519
 
Largest minimal prime factor: 47 of 12878611
All prime factors for this number: 47 101 2713
</pre>
 
{{out}}
Sample output when the other number is found first.
<pre>
Thread 0: found larger: 3 of 12757923
Thread 2: found larger: 29 of 15808973
Thread 1: found larger: 47 of 12878893
Thread 0: not larger: 47 of 12878611
Thread 2: not larger: 7 of 15780709
Thread 1: not larger: 3 of 12757923
Thread 3: not larger: 3 of 197622519
 
Largest minimal prime factor: 47 of 12878893
All prime factors for this number: 47 274019
</pre>
 
=={{header|zkl}}==
Using 64 bit ints and "green"/co-op threads. Using native threads is bad in this case because spawning a bunch of threads (ie way more than there are cpus) really clogs the system and actually slows things down. Strands (zkl speak for green threads) queues up computations for a limited pool of threads, and, as each thread finishes a job, it reads from the queue for the next computation to perform. Strands, as they start up, kick back a future, which can be forced (ie waited on until a result is available) by evaluating it, in this case, by doing a future.noop().
<langsyntaxhighlight lang="zkl">fcn factorize(x,y,z,etc){
xyzs:=vm.arglist;
fs:=xyzs.apply(factors.strand) // queue up factorizing for x,y,...
Line 1,793 ⟶ 2,924:
[0..].zip(fs).filter(fcn([(n,x)],M){ x==M }.fp1((0).max(fs))) // find max of mins
.apply('wrap([(n,_)]){ xyzs[n] }) // and pluck src from arglist
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">factorize(12757923,12878611,12757923,15808973,15780709,197622519).println();
// do a bunch so I can watch the system monitor
factorize( (0).pump(5000,List,fcn{(1000).random() }).xplode() ).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,803 ⟶ 2,934:
</pre>
[[Prime decomposition#zkl]]
<langsyntaxhighlight lang="zkl">fcn factors(n){ // Return a list of factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
Line 1,815 ⟶ 2,946:
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
}</langsyntaxhighlight>
 
 
{{omit from|6502 Assembly|Technically the language does this at a sub-instruction level but that doesn't count}}
{{omit from|68000 Assembly}}
{{omit from|AWK}}
{{omit from|AutoHotkey}}
2,122

edits