The following is simple code for computing prime numbers:
#define END 100000000
// Only pass odd values to this function
int is_prime(uint32_t v)
{
uint32_t end = sqrt(v);
for (uint32_t i = 3; i <= end; i += 2) {
if ((v % i) == 0) {
return 0;
}
}
return 1;
}
int main(int argc, char **argv)
{
// We'll grab 2 as it's the only even prime
int prime_count = 1;
uint32_t bracket = 10;
#pragma omp parallel for num_threads(4)
for (uint32_t i = 3; i < END; i += 2) {
if (i > bracket) {
printf("%12d\t%12d\n", bracket, prime_count);
bracket *= 10;
}
if (is_prime(i)) {
prime_count++;
}
}
printf("%12d\t%12d\n", bracket, prime_count);
return 0;
}
Our task is to use OpenMP pragmas to speed up the computation, since looping through 100,000,000 integers will take a long time. I tried putting the #pragma statement where I currently have it in my pasted code, and when I run the code I get the following output:
10 4
10 1
10 4
10 4
100 25
1000 25
10000 25
100000 25
10000000 262
1410065408 5737822
Clearly seeing this as incorrect, I tried putting a #pragma above the for loop in the is_prime() function, but I got compiler error saying
error: "invalid branch to/from OpenMP structured block".
I realize this error is coming from the thread potentially entering the if statement and returning 0 in the middle of the parallel operations. The thread gets terminated prematurely and the entire operation comes apart. I feel like its most appropriate to put the #pragma inside the function call, as it can cut the run time down by v/4 for each call to the function. However, I do not know the proper syntax to do this. If someone can please help me out I'd greatly appreciate it. Thanks