You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.2 KiB
C
47 lines
1.2 KiB
C
9 months ago
|
#include <mpi.h>
|
||
|
#include <stdio.h>
|
||
|
int main(int argc, char *argv[]) {
|
||
|
int N, k;
|
||
|
int my_rank, commsize;
|
||
|
double result, buf = 0;
|
||
|
|
||
|
MPI_Init(&argc,&argv);
|
||
|
|
||
|
MPI_Comm_size(MPI_COMM_WORLD, &commsize);
|
||
|
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
|
||
|
|
||
|
/* Головной процесс */
|
||
|
if (my_rank == 0) {
|
||
|
scanf("%d", &N);
|
||
|
k = N / commsize;
|
||
|
|
||
|
for (int i = 1; i < commsize; ++i)
|
||
|
MPI_Send(&k, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
|
||
|
|
||
|
/* Считаем члены суммы, оставшиеся после распределения (в случае commsize < N - считаем всю сумму тут) */
|
||
|
for (int i = k * (commsize - 1) + 1; i <= N; i++)
|
||
|
result += 1 / (double)i;
|
||
|
|
||
|
/* Получаем результаты подсчета от всех процессов */
|
||
|
printf("[0] result = %f\n", result);
|
||
|
for (int i = 1; i < commsize; ++i) {
|
||
|
MPI_Recv(&buf, 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, NULL);
|
||
|
printf("[%d] result = %f\n", i, buf);
|
||
|
result += buf;
|
||
|
}
|
||
|
|
||
|
printf("result = %f\n", result);
|
||
|
|
||
|
}
|
||
|
else {
|
||
|
MPI_Recv(&k, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, NULL);
|
||
|
|
||
|
for (int i = (my_rank - 1) * k + 1; i < my_rank * k + 1; ++i)
|
||
|
result += 1 / (double)i;
|
||
|
|
||
|
MPI_Send(&result, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
|
||
|
}
|
||
|
|
||
|
MPI_Finalize();
|
||
|
}
|