#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int rank, size;
int local_max, global_max;
int array[] = {5, 12, 7, 21, 9, 19, 3, 8}; // Example array
int n = sizeof(array) / sizeof(array[0]); // Size of the array
int local_size;
// Initialize MPI environment
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Divide the array among processes
local_size = n / size; // Assumes the array size is divisible by number of processes
int local_array[local_size];
MPI_Scatter(array, local_size, MPI_INT, local_array, local_size, MPI_INT, 0, MPI_COMM_WORLD);
// Find the local maximum
local_max = local_array[0];
for (int i = 1; i < local_size; i++) {
if (local_array[i] > local_max) {
local_max = local_array[i];
}
}
// Use MPI_Reduce to find the global maximum
MPI_Reduce(&local_max, &global_max, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
// The root process (rank 0) prints the global maximum
if (rank == 0) {
printf("The largest element in the array is: %d\n", global_max
); }
// Finalize MPI environment
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPG1waS5oPgojaW5jbHVkZSA8c3RkaW8uaD4KI2luY2x1ZGUgPHN0ZGxpYi5oPgoKaW50IG1haW4oaW50IGFyZ2MsIGNoYXIqKiBhcmd2KSB7CiAgICBpbnQgcmFuaywgc2l6ZTsKICAgIGludCBsb2NhbF9tYXgsIGdsb2JhbF9tYXg7CiAgICBpbnQgYXJyYXlbXSA9IHs1LCAxMiwgNywgMjEsIDksIDE5LCAzLCA4fTsgLy8gRXhhbXBsZSBhcnJheQogICAgaW50IG4gPSBzaXplb2YoYXJyYXkpIC8gc2l6ZW9mKGFycmF5WzBdKTsgLy8gU2l6ZSBvZiB0aGUgYXJyYXkKICAgIGludCBsb2NhbF9zaXplOwoKICAgIC8vIEluaXRpYWxpemUgTVBJIGVudmlyb25tZW50CiAgICBNUElfSW5pdCgmYXJnYywgJmFyZ3YpOwogICAgTVBJX0NvbW1fcmFuayhNUElfQ09NTV9XT1JMRC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