fork download
  1. #include <mpi.h>
  2. #include <stdio.h>
  3.  
  4. int main(int argc, char** argv) {
  5. int rank, size;
  6. int I = 1; // Starting value
  7. int p = 10; // Ending value (inclusive)
  8. int local_value, global_sum;
  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. // Assign values to processes
  16. local_value = rank + I;
  17.  
  18. // Perform sum reduction
  19. MPI_Reduce(&local_value, &global_sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
  20.  
  21. // Process 0 computes and prints the result
  22. if (rank == 0) {
  23. printf("Sum computed by reduction: %d\n", global_sum);
  24.  
  25. // Compute the expected sum using the formula p(p+1)/2
  26. int expected_sum = p * (p + 1) / 2;
  27. printf("Expected sum using formula p(p+1)/2: %d\n", expected_sum);
  28.  
  29. // Double-check the values match
  30. if (global_sum == expected_sum) {
  31. printf("The computed sum matches the expected sum.\n");
  32. } else {
  33. printf("The computed sum does not match the expected sum!\n");
  34. }
  35. }
  36.  
  37. // Finalize MPI
  38. MPI_Finalize();
  39. return 0;
  40. }
  41.  
Success #stdin #stdout #stderr 0.31s 40700KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted