-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsieve-v-25.cpp
59 lines (53 loc) · 1.51 KB
/
sieve-v-25.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
#include <bits/stdc++.h>
#include <chrono>
#include <stdio.h>
#include <math.h>
#include <omp.h>
using namespace std;
using namespace std::chrono;
typedef int32_t Number;
int eratosthenes(int lastNumber)
{
omp_set_num_threads(omp_get_num_procs());
const Number lastNumberSqrt = (int)sqrt((double)lastNumber);
Number memorySize = (lastNumber-1)/2;
char* isPrime = new char[memorySize+1];
#pragma omp parallel for
for (Number i = 0; i <= memorySize; i++)
isPrime[i] = 1;
#pragma omp parallel for schedule(dynamic)
for (Number i = 3; i <= lastNumberSqrt; i += 2)
if (isPrime[i/2])
#pragma omp parallel for
for (Number j = i*i; j <= lastNumber; j += 2*i)
isPrime[j/2] = 0;
int found = lastNumber >= 2 ? 1 : 0;
// introduce a data race, because multiple threads could try to update the shared variable at the same time.
#pragma omp parallel for reduction(+:found)
for (Number i = 1; i <= memorySize; i++)
found += isPrime[i];
delete[] isPrime;
return found;
}
int main(int argc, char *argv[])
{
int n = 100;
if (argc > 1)
{
try
{
n = stoi(argv[1]);
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
}
auto start = high_resolution_clock::now();
eratosthenes(n);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << duration.count();
return 0;
}
// g++ -std=c++11 basic.cpp && ./a.out