/* File: twinprimes2.cpp Multi-threaded version to find a twin prime between begin and end. This version can be buggy because writes to found, first and second can be made simultanenously by different threads. compile with: g++ twinprimes2.cpp -o twinprimes2 to get timing, run wiht: time ./twinprimes2 */ #include #include #include int isPrime (unsigned int n) { unsigned int m = sqrt(n) ; for (unsigned int k=2 ; k <= m ; k++) { if (n % k == 0) return 0 ; } return 1 ; } int main() { int found=0 ; int begin=10000000 ; // 10 million int end=20000000 ; // 20 million int first, second ; #pragma omp parallel shared(found,begin,end,first,second) { #pragma omp for schedule(dynamic) reduction(||:found) for(int i=begin ; i < end ; i++) { if ( isPrime(i) && isPrime(i+2) ) { found = 1 ; // Danger!! first = i ; second = i+2 ; } } } // end parallel region if (found) { printf("Yes, there are twin primes between %d and %d.\n", begin, end) ; printf("One example is %d and %d.\n", first, second) ; } else { printf("No, there are no twin primes between %d and %d.\n", begin, end) ; } return 0 ; }