#include #include #include #define START 0 #define END 100 int main(int argc, char** argv) { int rank, size; /* initialize MPI */ MPI_Init(&argc, &argv); /* get the rank (process id) and size (number of processes) */ MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); /* calculate the start and end points by evenly dividing the range */ int start = ((END - START) / size) * rank; int end = start + ((END - START) / size) - 1; /* the last process needs to do all remaining ones */ if (rank == (size - 1)) { end = END; } /* do the calculation */ int sum = 0, i; for (i = start; i <= end; i++) { sum += i; } /* debugging output */ printf("Process %d: sum(%d, %d) = %d\n", rank, start, end, sum); /* do the reduction */ int final = -1; MPI_Reduce(&sum, &final, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); /* now have process 0 display the results */ if (rank == 0) { printf("The final sum = %d (rank = %d).\n", final, rank); } /* quit MPI */ MPI_Finalize(); return 0; }