Parallel calculations: Difference between revisions

Added FreeBASIC
mNo edit summary
(Added FreeBASIC)
 
(5 intermediate revisions by 3 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 219:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 252:
Console.WriteLine(string.Join(" ", factors[whatIndexIsThat]));
}
}</langsyntaxhighlight>
{{out}}
<pre>12878611 has the largest minimum prime factor: 47
Line 259:
Another version, using Parallel.For:
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 282:
foreach (int list in l[j])
Console.Write(" "+list);
}</langsyntaxhighlight>
{{out}}
<pre>Number 12878611 has largest minimal factor:
Line 292:
This uses C++11 features including lambda functions.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iterator>
#include <vector>
Line 348:
});
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 356:
 
=={{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 541:
{{libheader| Velthuis.BigIntegers}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Parallel_calculations;
 
Line 635:
 
readln;
end.</langsyntaxhighlight>
 
=={{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 682:
My_pid ! Result
end ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 690:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open PrimeDecomp // Has the decompose function from the Prime decomposition task
 
Line 708:
List.iter (printf "%d ") primeList
 
showLargestMinPrimeFactor data</langsyntaxhighlight>
 
{{out}}
Line 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 738:
"Number with largest min. factor is " swap number>string append
", with factors: " append write .
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 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 753:
"Number with largest min. factor is " swap number>string append
", with factors: " append write .
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 763:
Using OpenMP (compile with -fopenmp)
 
<langsyntaxhighlight lang="fortran">
program Primes
 
Line 818:
 
end program Primes
</syntaxhighlight>
</lang>
 
{{out}}
Line 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 927 ⟶ 980:
}
return res
}</langsyntaxhighlight>
{{out}}
<pre>
Line 936 ⟶ 989:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Parallel.Strategies (parMap, rdeepseq)
import Control.DeepSeq (NFData)
import Data.List (maximumBy)
Line 982 ⟶ 1,035:
 
main :: IO ()
main = print $ minPrimes nums</langsyntaxhighlight>
{{out}}
<pre>(115797840077099,[212609249,544651])</pre>
Line 990 ⟶ 1,043:
The following only works in Unicon.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
threads := []
L := list(*A)
Line 1,007 ⟶ 1,060:
link factors
</syntaxhighlight>
</lang>
 
Sample run:
Line 1,018 ⟶ 1,071:
=={{header|J}}==
The code at [http://code.jsoftware.com/wiki/User: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 1,024 ⟶ 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;
Line 1,064 ⟶ 1,117:
return new long[]{n, n};
}
}</langsyntaxhighlight>
 
<pre>12878611 has the largest minimum prime factor: 47</pre>
Line 1,072 ⟶ 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 1,089 ⟶ 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,131 ⟶ 1,184:
console.log("The number with the relatively largest factors is: " + n + " : " + factors);
}
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
using Primes
 
Line 1,156 ⟶ 1,209:
answer = maximum(keys(mins))
println("The number that has the largest minimum prime factor is $(mins[answer]), with a smallest factor of $answer")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,163 ⟶ 1,216:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.51
 
import java.util.stream.Collectors
Line 1,214 ⟶ 1,267:
println(" ${result.first} whose prime factors are ${result.third}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,224 ⟶ 1,277:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">hasSmallestFactor[data_List]:=Sort[Transpose[{ParallelTable[FactorInteger[x][[1, 1]], {x, data}],data}]][[1, 2]]</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 1,232 ⟶ 1,285:
Note that the program must be compiled with option <code>--threads:on</code>.
 
<langsyntaxhighlight Nimlang="nim">import strformat, strutils, threadpool
 
const Numbers = [576460752303423487,
Line 1,285 ⟶ 1,338:
echo ""
echo "The first number with the largest minimum prime factor is: ", result
echo "Its factors are: ", result.factors(maxMinfact).join(", ")</langsyntaxhighlight>
 
{{out}}
Line 1,305 ⟶ 1,358:
Note that program must be compiled with option <code>--threads:on</code>.
 
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils, threadpool
 
{.experimental: "parallel".}
Line 1,355 ⟶ 1,408:
echo ""
echo "The first number with the largest minimum prime factor is: ", result
echo "Its factors are: ", result.factors(maxMinfact).join(", ")</langsyntaxhighlight>
 
{{out}}
Line 1,370 ⟶ 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,382 ⟶ 1,435:
=={{header|ooRexx}}==
This program calls the programs shown under REXX (modified for ooRexx and slightly expanded).
<langsyntaxhighlight lang="oorexx">/* Concurrency in ooRexx. Example of early reply */
object1 = .example~new
object2 = .example~new
Line 1,396 ⟶ 1,449:
When which=1 Then Call pd1 bot top
When which=2 Then Call pd2 bot top
End </langsyntaxhighlight>
{{out}}
<pre>Start primes1: 09:25:25
Line 1,415 ⟶ 1,468:
1 primes found.
PD2 took 1.109000 seconds</pre>
<langsyntaxhighlight lang="rexx">
/*PD1 REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/
Call Time 'R'
Line 1,460 ⟶ 1,513:
/* [?] 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. */</langsyntaxhighlight>
<langsyntaxhighlight 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*/
Line 1,510 ⟶ 1,563:
/* [?] 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. */</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
'CONFIGURATION
'=============
Line 1,695 ⟶ 1,748:
 
print str((t2-t1)/freq,3) " secs " numbers(n) " " f 'number with highest prime factor
</syntaxhighlight>
</lang>
 
=={{header|PARI/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).
{{works with|PARI/GP|2.6.2+}}
<langsyntaxhighlight lang="parigp">v=pareval(vector(1000,i,()->factor(2^i+1)[1,1]));
vecmin(v)</langsyntaxhighlight>
 
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/factor vecmax/;
use threads;
use threads::shared;
Line 1,723 ⟶ 1,776:
my($tnum, $n) = @_;
push @results, shared_clone([$n, factor($n)]);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,733 ⟶ 1,786:
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>-- demo/rosetta/ParallelCalculations.exw
<span style="color: #000080;font-style:italic;">--
include mpfr.e
-- demo\rosetta\ParallelCalculations.exw
sequence res
-- =====================================
constant res_cs = init_cs() -- critical section
--
 
-- Proof that more threads can make things faster...
procedure athread()
--</span>
mpz z = mpz_init()
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (threads)</span>
while true do
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
integer found = 0
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span>
enter_cs(res_cs)
<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>
for i=1 to length(res) do
if integer(res[i]) then
<span style="color: #008080;">procedure</span> <span style="color: #000000;">athread</span><span style="color: #0000FF;">()</span>
found = i
<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>
res[i] = {}
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
exit
<span style="color: #004080;">integer</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
end if
<span style="color: #7060A8;">enter_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
end for
<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>
leave_cs(res_cs)
<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>
if not found then exit end if
<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>
mpz_ui_pow_ui(z,2,found)
<span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
mpz_add_ui(z,z,1)
<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>
sequence r = mpz_prime_factors(z, 1_000_000)
<span style="color: #008080;">exit</span>
enter_cs(res_cs)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
res[found] = r
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
leave_cs(res_cs)
<span style="color: #7060A8;">leave_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
end while
<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>
exit_thread(0)
<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>
end procedure
<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>
for nthreads=1 to 5 do
<span style="color: #7060A8;">enter_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
atom t0 = time()
<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>
res = tagset(100)
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
sequence threads = {}
<span style="color: #7060A8;">leave_cs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res_cs</span><span style="color: #0000FF;">)</span>
for i=1 to nthreads do
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
threads = append(threads,create_thread(routine_id("athread"),{}))
<span style="color: #7060A8;">exit_thread</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
wait_thread(threads)
integer k = largest(res,true)
<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>
string e = elapsed(time()-t0)
<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>
printf(1,"largest is 2^%d+1 with smallest factor of %d (%d threads, %s)\n",
<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>
{k,res[k][1][1],nthreads,e})
<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>
end for
<span style="color: #004080;">sequence</span> <span style="color: #000000;">threads</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
delete_cs(res_cs)</lang>
<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>
Line 1,795 ⟶ 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,814 ⟶ 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,825 ⟶ 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,856 ⟶ 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,875 ⟶ 1,939:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Structure IO_block
ThreadID.i
StartSeamaphore.i
Line 1,962 ⟶ 2,026:
end_of_data:
EndDataSection
</syntaxhighlight>
</lang>
[[image:PB_Parallel_Calculations.png]]
 
Line 1,970 ⟶ 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 2,014 ⟶ 2,078:
if __name__ == '__main__':
main()</langsyntaxhighlight>
 
{{out}}
Line 2,032 ⟶ 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 2,078 ⟶ 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 2,107 ⟶ 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}}==
Line 2,126 ⟶ 2,190:
 
Using the <tt>prime-factors</tt> routine as defined in the [[Prime_decomposition#Raku|prime decomposition]] task.
<syntaxhighlight lang="raku" perl6line>my @nums = 64921987050997300559, 70251412046988563035, 71774104902986066597,
83448083465633593921, 84209429893632345702, 87001033462961102237,
87762379890959854011, 89538854889623608177, 98421229882942378967,
Line 2,194 ⟶ 2,258:
$factor = find-factor( $n, $constant + 1 ) if $n == $factor;
$factor;
}</langsyntaxhighlight>
{{out|Typical output}}
<pre> 64921987050997300559 factors: 736717 88123373087627
Line 2,257 ⟶ 2,321:
 
=={{header|Rust}}==
<langsyntaxhighlight 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
Line 2,287 ⟶ 2,351:
println!("The largest minimal factor is {}", max);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,296 ⟶ 2,360:
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 2,308 ⟶ 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 2,356 ⟶ 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 2,370 ⟶ 2,434:
=={{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">
<lang Standard ML>
structure TTd = Thread.Thread ;
structure TTm = Thread.Mutex ;
Line 2,429 ⟶ 2,493:
 
end ;
</syntaxhighlight>
</lang>
call and output - interpreter
<syntaxhighlight lang="standard ml">
<lang Standard ML>
> threadedBigPrime [ 62478923478923409323, 69478923478923409313, 79234790234098402349,
33498023480920234793, 92834098234098023409, 31908234098234098243,
Line 2,443 ⟶ 2,507:
> List.map (List.foldr IntInf.* 1 ) it ;
val it = [62478923478925971503, 62478923478923409323]: IntInf.int list
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
Line 2,449 ⟶ 2,513:
{{libheader|AttaSwift BigInt}}
 
<langsyntaxhighlight lang="swift">import BigInt
import Foundation
 
Line 2,522 ⟶ 2,586:
}
 
dispatchMain()</langsyntaxhighlight>
 
{{out}}
Line 2,552 ⟶ 2,616:
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 2,593 ⟶ 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 2,661 ⟶ 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 2,677 ⟶ 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 2,688 ⟶ 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 2,698 ⟶ 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 2,710 ⟶ 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}}
2,122

edits