fork download
  1. #include <mpi.h>
  2. #include <omp.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <time.h>
  6.  
  7. int main(int argc, char** argv) {
  8. int rank, size, N, M, *array = NULL, local_sum = 0, global_sum = 0;
  9.  
  10. // Initialize MPI
  11. MPI_Init(&argc, &argv);
  12. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  13. MPI_Comm_size(MPI_COMM_WORLD, &size);
  14.  
  15. if (rank == 0) {
  16. // Input M and N
  17. printf("Enter the number of processes (M): ");
  18. scanf("%d", &M);
  19. printf("Enter the size of the array (N): ");
  20. scanf("%d", &N);
  21.  
  22. if (M > size) {
  23. printf("Error: M cannot be greater than the total number of MPI processes.\n");
  24. MPI_Abort(MPI_COMM_WORLD, 1);
  25. }
  26.  
  27. // Initialize the array with random integers
  28. array = (int*)malloc(N * sizeof(int));
  29. srand(time(0));
  30. for (int i = 0; i < N; i++) {
  31. array[i] = rand() % 100;
  32. }
  33. }
  34.  
  35. // Broadcast N to all processes
  36. MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);
  37.  
  38. // Scatter the array to all processes
  39. int local_size = N / size;
  40. int* local_array = (int*)malloc(local_size * sizeof(int));
  41. MPI_Scatter(array, local_size, MPI_INT, local_array, local_size, MPI_INT, 0, MPI_COMM_WORLD);
  42.  
  43. // Compute the partial sum using OpenMP
  44. #pragma omp parallel for reduction(+:local_sum)
  45. for (int i = 0; i < local_size; i++) {
  46. local_sum += local_array[i];
  47. }
  48.  
  49. // Reduce all partial sums to the global sum in Process 0
  50. MPI_Reduce(&local_sum, &global_sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
  51.  
  52. if (rank == 0) {
  53. printf("Total Sum of Array: %d\n", global_sum);
  54. free(array);
  55. }
  56.  
  57. free(local_array);
  58. MPI_Finalize();
  59. return 0;
  60. }
  61.  
Success #stdin #stdout #stderr 0.26s 40856KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted