Write an MPI program to find the min and max number from randomly generated 1000 numbers (stored in array) on a cluster (Hint: Use MPI_Reduce)
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define ARRAY_SIZE 1000
int main(int argc, char** argv) {
int rank, size;
int array[ARRAY_SIZE];
int local_min, local_max, global_min, global_max;
// Initialize MPI
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Seed random number generator
srand(rank * (unsigned)time(NULL));
// Generate random numbers for the local array
for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = rand();
}
// Find local min and max
local_min = local_max = array[0];
for (int i = 1; i < ARRAY_SIZE; i++) {
if (array[i] < local_min) {
local_min = array[i];
}
if (array[i] > local_max) {
local_max = array[i];
}
}
// Reduce local min and max to global min and max
MPI_Reduce(&local_min, &global_min, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
MPI_Reduce(&local_max, &global_max, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("Global Minimum: %d\n", global_min);
printf("Global Maximum: %d\n", global_max);
}
// Finalize MPI
MPI_Finalize();
return 0;
}
Comments
Post a Comment