-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
74 lines (58 loc) · 1.76 KB
/
main.cpp
File metadata and controls
74 lines (58 loc) · 1.76 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
#include <iostream>
#include <fstream>
#include <thread>
#include <vector>
#include <chrono>
#include <numeric>
#include <future>
#include <cmath>
bool isPrime(int n) {
if (n<=1 || (n%2==0 && n!=2)) return false;
const int s=sqrt(n);
for (int i=3;i<=s;i++){
if(n%i==0) return false;
}
return true;
}
void compute(int start, int end, int threadId, std::vector<int>& result, int& partialSum) {
for (int i = start; i <= end; ++i) {
if (isPrime(i)) {
result.push_back(i);
partialSum +=i;
}
}
}
int main() {
using namespace std;
//n is number of Threads, (S,E) is the range.
const int num = 8;
const int S = 1;
const int E = 100000000;
vector<thread> threads;
vector<vector<int>> partial(num);
vector<int> sums(num);
int totalPrimes=0;
auto start = chrono::high_resolution_clock::now();
for (int i = 0; i < num; ++i) {
int start = S + (i * (E - S + 1) / num);
int end = S + ((i + 1) * (E - S + 1) / num) - 1;
threads.emplace_back(compute, start, end, i, ref(partial[i]), ref(sums[i]));
}
// Wait for all threads to finish
for (auto& thread : threads) thread.join();
//finish time
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(stop - start);
ofstream myfile;
myfile.open("primes.txt");
myfile << "<" << duration.count() << "ms> ";
for (const auto& list : partial) totalPrimes+=list.size();
myfile << "<" << totalPrimes << "> ";
int primeSum=accumulate(sums.begin(), sums.end(), 0);
myfile << "<" << primeSum << ">\n<";
vector<int> destinationVector(partial[num-1].end() - 10, partial[num-1].end());
for (int i = 0; i < 10; ++i) myfile << destinationVector[i] << " ";
myfile << ">" << endl;
myfile.close();
return 0;
}