#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>

#define STEPS 27720

int main(int argc, char *argv[])
{
   int rank,nproc,start,end,i;
   double total, result, *all_results;

   MPI_Init(&argc,&argv);
   MPI_Comm_size(MPI_COMM_WORLD,&nproc);
   MPI_Comm_rank(MPI_COMM_WORLD,&rank);

   total=0;
   start=rank*(STEPS/(double)nproc);
   end=(rank+1)*(STEPS/(double)nproc)-1;
   if (rank==0) all_results=malloc(nproc*sizeof(double));

   for(i=start;i<=end;i++)
      total+=exp(-pow(10.0*((i+0.5)/(STEPS+1)),2));

   MPI_Gather(&total,1,MPI_DOUBLE,all_results,1,MPI_DOUBLE,
              0,MPI_COMM_WORLD);
   if (rank==0)
     for(i=0;i<nproc;i++)
       printf("Total from process %d is %f\n",i,all_results[i]);

   MPI_Reduce(&total,&result,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);

   if (rank==0)
     printf("Grand total is %f and integral is %f\n",result,
             10*result/STEPS);

   MPI_Finalize();
}
