fork download
  1. #include <mpi.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5.  
  6. int main(int argc, char** argv) {
  7. MPI_Init(&argc, &argv); // Initialize the MPI environment
  8.  
  9. int rank, size;
  10. MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get the rank of the process
  11. MPI_Comm_size(MPI_COMM_WORLD, &size); // Get the total number of processes
  12.  
  13. if (size != 5) {
  14. if (rank == 0) {
  15. printf("This program requires exactly 5 processes.\n");
  16. }
  17. MPI_Finalize();
  18. return 1;
  19. }
  20.  
  21. // Generate a unique seed for each process
  22. unsigned int seed = time(NULL) + rank; // Unique seed using current time and rank
  23. srand(seed);
  24.  
  25. // Generate a pseudo-random number
  26. int random_number = rand();
  27. printf("Process %d generated random number: %d\n", rank, random_number);
  28.  
  29. // Find the maximum using MPI_Reduce
  30. int max_random_number;
  31. MPI_Reduce(&random_number, &max_random_number, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
  32.  
  33. // Root process prints the maximum random number
  34. if (rank == 0) {
  35. printf("The maximum random number is: %d\n", max_random_number);
  36. }
  37.  
  38. MPI_Finalize(); // Finalize the MPI environment
  39. return 0;
  40. }
  41.  
Success #stdin #stdout #stderr 0.32s 40800KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted