#include <iostream>
#include <cmath>
#include <vector>
#include <mpi.h>

#define STEPS 27720

int main(int argc, char *argv[])
{
   int rank,nproc,start,end,i;
   double total, result;
   std::vector<double> 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.resize(nproc);

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

   std::cout << "Rank " << rank << " total " << total << std::endl;
   
   // could use all_results.data() in place of &all_results[0]
   MPI_Gather(&total,1,MPI_DOUBLE,&all_results[0],1,MPI_DOUBLE,
              0,MPI_COMM_WORLD);
   if (rank==0)
     for(i=0;i<nproc;i++)
       std::cout << "Total from process " << i << " is "
                 << all_results[i] << std::endl;

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

   if (rank==0)
     std::cout << "Grand total is " << result << " and integral is "
                                 << 10*result/STEPS << std::endl;

   MPI_Finalize();
}
