-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-primes.cpp
More file actions
70 lines (55 loc) · 1.08 KB
/
generate-primes.cpp
File metadata and controls
70 lines (55 loc) · 1.08 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
#include <fstream>
#include <math.h>
#include <thread>
#include <mutex>
#include <vector>
#include <algorithm>
#define NUM_THREADS 8
int num;
std::mutex num_mutex;
std::mutex vec_mutex;
std::vector<int> primes;
static auto check_prime_threaded() -> void {
bool isPrime;
int numSqrt;
int current_num;
int i;
while (num <= 250000000){
num_mutex.lock();
current_num = num;
num += 2;
num_mutex.unlock();
isPrime = true;
numSqrt = sqrt(current_num);
for (i = 2; i < numSqrt; i++)
if (current_num % i == 0){
isPrime = false;
break;
}
if (isPrime){
vec_mutex.lock();
primes.push_back(current_num);
vec_mutex.unlock();
}
}
}
auto main() -> int {
std::ofstream file;
file.open("primes.txt");
file << 2 << "\n";
num = 3;
std::thread threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++){
threads[i] = std::thread(check_prime_threaded);
}
for (int i = 0; i < NUM_THREADS; i++){
threads[i].join();
}
std::sort(primes.begin(), primes.end());
for (auto& p : primes){
file << p << '\n';
}
file.close();
primes.clear();
return 0;
}