-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer01c-max-div.cpp
More file actions
129 lines (87 loc) · 2.44 KB
/
Copy pathexer01c-max-div.cpp
File metadata and controls
129 lines (87 loc) · 2.44 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
MAXIMUM NUMBER OF DIVISORS
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <thread>
#include <mutex>
#include "mylib-time.hpp"
using namespace std;
struct WorkerArg {
int iStart;
int iEnd;
WorkerArg(int iStart = 0, int iEnd = 0): iStart(iStart), iEnd(iEnd)
{
}
};
class FinalResult {
public:
int value = 0;
int numDiv = 0;
private:
std::mutex mut;
public:
void update(int value, int numDiv) {
// Synchronize whole function
std::unique_lock<std::mutex> lk(mut);
if (this->numDiv < numDiv) {
this->numDiv = numDiv;
this->value = value;
}
}
};
void workerFunc(WorkerArg* arg, FinalResult* res) {
int resValue = 0;
int resNumDiv = 0;
for (int i = arg->iStart; i <= arg->iEnd; ++i) {
int numDiv = 0;
for (int j = i / 2; j > 0; --j)
if (i % j == 0)
++numDiv;
if (resNumDiv < numDiv) {
resNumDiv = numDiv;
resValue = i;
}
}
res->update(resValue, resNumDiv);
}
void prepare(
int rangeStart, int rangeEnd,
int numThreads,
vector<std::thread>& lstTh,
vector<WorkerArg>& lstWorkerArg
) {
lstTh.resize(numThreads);
lstWorkerArg.resize(numThreads);
int rangeA, rangeB, rangeBlock;
rangeBlock = (rangeEnd - rangeStart + 1) / numThreads;
rangeA = rangeStart;
for (int i = 0; i < numThreads; ++i, rangeA += rangeBlock) {
rangeB = rangeA + rangeBlock - 1;
if (i == numThreads - 1)
rangeB = rangeEnd;
lstWorkerArg[i] = WorkerArg(rangeA, rangeB);
}
}
int main() {
constexpr int RANGE_START = 1;
constexpr int RANGE_END = 100000;
constexpr int NUM_THREADS = 8;
vector<std::thread> lstTh;
vector<WorkerArg> lstWorkerArg;
FinalResult finalRes;
prepare(RANGE_START, RANGE_END, NUM_THREADS, lstTh, lstWorkerArg);
auto tpStart = mylib::HiResClock::now();
for (int i = 0; i < NUM_THREADS; ++i) {
lstTh[i] = std::thread(&workerFunc, &lstWorkerArg[i], &finalRes);
}
for (auto&& th : lstTh) {
th.join();
}
auto timeElapsed = mylib::HiResClock::getTimeSpan(tpStart);
cout << "The integer which has largest number of divisors is " << finalRes.value << endl;
cout << "The largest number of divisor is " << finalRes.numDiv << endl;
cout << "Time elapsed = " << timeElapsed.count() << endl;
return 0;
}