#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define SIZE 8
int main(int argc, char *argv[]) {
int rank, size;
int numbers[SIZE][3];
int lsum = 0, gsum = 0; //local_sum and global_sum
int count_per_process;
int *recvbuf;
// MPI environment
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Process 0 reads the input numbers
if (rank == 0) {
printf("Enter the numbers:\n"); //inputs 3 integers for (int i = 0; i < SIZE; i++) {
scanf("%d %d %d", &numbers
[i
][0], &numbers
[i
][1], &numbers
[i
][2]); }
}
MPI_Bcast(numbers, SIZE * 3, MPI_INT, 0, MPI_COMM_WORLD);
count_per_process = SIZE / size;
// Each process calculates its local sum
for (int i = rank * count_per_process; i < (rank + 1) * count_per_process; i++) {
for (int j = 0; j < 3; j++) {
lsum += numbers[i][j];
}
printf("Process %d partial sum of set %d: %d\n", rank
, i
, lsum
); }
// Reduce local sums to global sum at process 0
MPI_Reduce(&lsum, &gsum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
//prints the global sum
if (rank == 0) {
printf("Global sum: %d\n", gsum
); }
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPG1waS5oPgoKI2RlZmluZSBTSVpFIDggCgppbnQgbWFpbihpbnQgYXJnYywgY2hhciAqYXJndltdKSB7CiAgICBpbnQgcmFuaywgc2l6ZTsKICAgIGludCBudW1iZXJzW1NJWkVdWzNdOwogICAgaW50IGxzdW0gPSAwLCBnc3VtID0gMDsgLy9sb2NhbF9zdW0gYW5kIGdsb2JhbF9zdW0KICAgIGludCBjb3VudF9wZXJfcHJvY2VzczsKICAgIGludCAqcmVjdmJ1ZjsgCgogICAgLy8gTVBJIGVudmlyb25tZW50CiAgICBNUElfSW5pdCgmYXJnYywgJmFyZ3YpOwogICAgTVBJX0NvbW1fcmFuayhNUElfQ09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