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

int main(int argc, char ** argv)
{
    int n, rank, size;
    double data;
    double *send_buf, *recv_buf;
    
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    
    recv_buf = (double *) malloc(size*sizeof(double)); // allocate memory
    send_buf = (double *) malloc(size*sizeof(double));
    
    data = rank*rank + 1.0; // generate data on different procs
    MPI_Gather(&data,    1, MPI_DOUBLE, recv_buf, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    
    if (rank == 0){
        printf ("[Gather()]:\n");
        for (n = 0; n < size; n++) printf ("rnd[%d] = %f\n",n,recv_buf[n]);
    }
    
    if (rank == 0){
        for (n = 0; n < size; n++) send_buf[n] = n*n - 1.0; // Generate “size” random numbers
    }
    
    MPI_Scatter(send_buf, 1, MPI_DOUBLE, &data,    1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    
    printf ("[Scatter, proc #%d] = %f\n",rank,data);
    
    MPI_Finalize();
    return 0;
}
