#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>

/*******************************************************
An OpenMP version of a threaded program to compute PI.
********************************************************/
main ()
{
  int npoints = 1000000;
  int sum = 0;
  int i, tid;
  double rand_x, rand_y;
  double computed_pi;
  int seed = 1;
  double time_start, time_end;
  struct timeval tv;
  struct timezone tz;

  gettimeofday(&tv, &tz);
  time_start = (double)tv.tv_sec +
    (double)tv.tv_usec / 1000000.0;

#pragma omp parallel private(i, rand_x, rand_y) \
  firstprivate(seed) shared (npoints)		\
  reduction(+: sum) num_threads(4)
  {

#pragma omp for
    for (i = 0; i < npoints; i++) {
      rand_x =(double)(rand_r(&seed))/(double) RAND_MAX;
      rand_y =(double)(rand_r(&seed))/(double) RAND_MAX;
      if (((rand_x - 0.5) * (rand_x - 0.5) +
	   (rand_y - 0.5) * (rand_y - 0.5)) < 0.25)
	sum ++;
      seed *= i;
    }
    tid = omp_get_thread_num();
    printf("Thread id: %d sum: %d\n", tid, sum);
  }

  gettimeofday(&tv, &tz);
  time_end = (double)tv.tv_sec +
    (double)tv.tv_usec / 1000000.0;

  printf("Total hits %d of %d\n", sum, npoints);
  computed_pi = 4.0*(double) sum / ((double)(npoints));
  printf("Computed PI = %lf\n", computed_pi);
  printf("Elapsed time: %lf\n", time_end - time_start);
}
