#include <mpi.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
int rank, size, N, M, *array = NULL, local_sum = 0, global_sum = 0;
// Initialize MPI
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (rank == 0) {
// Input M and N
printf("Enter the number of processes (M): "); printf("Enter the size of the array (N): ");
if (M > size) {
printf("Error: M cannot be greater than the total number of MPI processes.\n"); MPI_Abort(MPI_COMM_WORLD, 1);
}
// Initialize the array with random integers
array
= (int*)malloc(N
* sizeof(int)); for (int i = 0; i < N; i++) {
}
}
// Broadcast N to all processes
MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);
// Scatter the array to all processes
int local_size = N / size;
int* local_array
= (int*)malloc(local_size
* sizeof(int)); MPI_Scatter(array, local_size, MPI_INT, local_array, local_size, MPI_INT, 0, MPI_COMM_WORLD);
// Compute the partial sum using OpenMP
#pragma omp parallel for reduction(+:local_sum)
for (int i = 0; i < local_size; i++) {
local_sum += local_array[i];
}
// Reduce all partial sums to the global sum in Process 0
MPI_Reduce(&local_sum, &global_sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("Total Sum of Array: %d\n", global_sum
); }
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPG1waS5oPgojaW5jbHVkZSA8b21wLmg+CiNpbmNsdWRlIDxzdGRpby5oPgojaW5jbHVkZSA8c3RkbGliLmg+CiNpbmNsdWRlIDx0aW1lLmg+CgppbnQgbWFpbihpbnQgYXJnYywgY2hhcioqIGFyZ3YpIHsKICAgIGludCByYW5rLCBzaXplLCBOLCBNLCAqYXJyYXkgPSBOVUxMLCBsb2NhbF9zdW0gPSAwLCBnbG9iYWxfc3VtID0gMDsKICAgCiAgICAvLyBJbml0aWFsaXplIE1QSQogICAgTVBJX0luaXQoJmFyZ2MsICZhcmd2KTsKICAgIE1QSV9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