<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0062)http://people.sc.fsu.edu/~burkardt/cpp_src/open_mp/prime_sum.C -->
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<META content="MSHTML 6.00.2900.2180" name=GENERATOR></HEAD>
<BODY><PRE># include <cstdlib>
# include <iostream>
# include <iomanip>
# include <omp.h>
using namespace std;
int main ( int argc, char *argv[] );
//****************************************************************************80
int main ( int argc, char *argv[] )
//****************************************************************************80
//
// Purpose:
//
// MAIN is the main program for PRIME_SUM.
//
// Discussion:
//
// The computational task is to sum the prime numbers from 1 to N.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 April 2009
//
// Author:
//
// John Burkardt
//
{
int i;
int j;
int n = 100000;
bool prime;
int total = 0;
double wtime;
cout << "\n";
cout << "PRIME_SUM\n";
cout << " C++/OpenMP version\n";
cout << "\n";
cout << " Sum the primes from 1 to " << n << "\n";
cout << " Number of processors available is " << omp_get_num_procs ( ) << "\n";
# pragma omp parallel
{
# pragma omp master
{
cout << "\n";
cout << " The number of threads is " << omp_get_num_threads ( ) << "\n";
}
}
wtime = omp_get_wtime ( );
# pragma omp parallel \
shared ( n ) \
private ( i, prime, j ) \
reduction ( + : total )
# pragma omp for
for ( i = 2; i <= n; i++ )
{
prime = true;
for ( j = 2; j < i; j++ )
{
if ( i % j == 0 )
{
prime = false;
break;
}
}
if ( prime )
{
total = total + i;
}
}
wtime = omp_get_wtime ( ) - wtime;
cout << "\n";
cout << " PRIME_SUM(2:" << n << ") = " << total << "\n";
cout << " Time = " << wtime << "\n";
cout << "\n";
cout << "PRIME_SUM\n";
cout << " Normal end of execution.\n";
return 0;
}
</PRE></BODY></HTML>
评论0