-
Notifications
You must be signed in to change notification settings - Fork 1
/
asyncPrimeSearching.cpp
71 lines (60 loc) · 2.02 KB
/
asyncPrimeSearching.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "asyncPrimeSearching.h"
#include "primeSearchingUtilities.h"
#include "PrimeTest.h"
std::vector<mpz_class> partitionBorders(int numberOfPartitions, mpz_class start, mpz_class finish) {
std::vector<mpz_class> results;
mpz_class total = finish - start;
results.push_back(start);
for (int i = 0; i != numberOfPartitions; ++i) {
results.push_back(results[i] + (total + i) / numberOfPartitions);
}
return results;
}
bool isEven(mpz_class test) {
return mpz_even_p(test.get_mpz_t());
}
struct primesInRange {
std::vector<mpz_class> operator()(mpz_class start, mpz_class finish) {
std::vector<mpz_class> primes;
if (isEven(start)) start++;
for (auto primeCandidate = start; primeCandidate < finish; primeCandidate += 2) {
if (isLikelyPrime(primeCandidate)) {
primes.push_back(primeCandidate);
}
}
return primes;
}
};
std::vector<mpz_class> gatherResultsFromThreads(
std::vector< std::future< std::vector<mpz_class> > > in) {
return
accumulate(concatenate<mpz_class>, std::vector<mpz_class>{},
map([](auto x) { return x.get(); },
std::move(in)
)
);
}
std::vector< std::future< std::vector<mpz_class> > >
asyncronouslyDistributePrimeTest(int threadTotal, mpz_class start, mpz_class finish) {
auto calculatePartition = [](mpz_class start, mpz_class end) {
return std::async(std::launch::async, primesInRange{}, start, end);
};
return
applyPairwise(calculatePartition,
partitionBorders(threadTotal,
start,
finish
)
);
}
std::vector<mpz_class> findPrimes(int threadTotal, mpz_class start, mpz_class finish) {
if (threadTotal == 0) return std::vector<mpz_class>{};
return
gatherResultsFromThreads(
asyncronouslyDistributePrimeTest(
threadTotal,
start,
finish
)
);
}