#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
int rank, size;
int I = 1; // Starting value
int p = 10; // Ending value (inclusive)
int local_value, global_sum;
// Initialize MPI
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Assign values to processes
local_value = rank + I;
// Perform sum reduction
MPI_Reduce(&local_value, &global_sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
// Process 0 computes and prints the result
if (rank == 0) {
printf("Sum computed by reduction: %d\n", global_sum
);
// Compute the expected sum using the formula p(p+1)/2
int expected_sum = p * (p + 1) / 2;
printf("Expected sum using formula p(p+1)/2: %d\n", expected_sum
);
// Double-check the values match
if (global_sum == expected_sum) {
printf("The computed sum matches the expected sum.\n"); } else {
printf("The computed sum does not match the expected sum!\n"); }
}
// Finalize MPI
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPG1waS5oPgojaW5jbHVkZSA8c3RkaW8uaD4KCmludCBtYWluKGludCBhcmdjLCBjaGFyKiogYXJndikgewogICAgaW50IHJhbmssIHNpemU7CiAgICBpbnQgSSA9IDE7IC8vIFN0YXJ0aW5nIHZhbHVlCiAgICBpbnQgcCA9IDEwOyAvLyBFbmRpbmcgdmFsdWUgKGluY2x1c2l2ZSkKICAgIGludCBsb2NhbF92YWx1ZSwgZ2xvYmFsX3N1bTsKCiAgICAvLyBJbml0aWFsaXplIE1QSQogICAgTVBJX0luaXQoJmFyZ2MsICZhcmd2KTsKICAgIE1QSV9Db21tX3JhbmsoTVBJX0NPTU1fV09STEQsICZyYW5rKTsKICAgIE1QSV9Db21tX3NpemUoTVBJX0NPTU1fV09STEQsICZzaXplKTsKCiAgICAvLyBBc3NpZ24gdmFsdWVzIHRvIHByb2Nlc3NlcwogICAgbG9jYWxfdmFsdWUgPSByYW5rICsgSTsKCiAgICAvLyBQZXJmb3JtIHN1bSByZWR1Y3Rpb24KICAgIE1QSV9SZWR1Y2UoJmxvY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