编写MPI程序,判断素数,进程0读取输入的n个整数(其中n刚好是进程数的倍数),并将这些整数平均分配到各个进程,最后进程0打印所有素数。
时间: 2024-04-30 22:22:23 浏览: 62
```c
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
int is_prime(int n) {
if (n < 2) return 0;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int n;
if (rank == 0) {
printf("请输入n:");
scanf("%d", &n);
if (n % size != 0) {
printf("n必须是进程数的倍数\n");
MPI_Finalize();
return 0;
}
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
int* nums = (int*)malloc(sizeof(int) * (n / size));
MPI_Scatter(nums, n / size, MPI_INT, nums, n / size, MPI_INT, 0, MPI_COMM_WORLD);
int count = 0;
for (int i = 0; i < n / size; i++) {
if (is_prime(nums[i])) count++;
}
int* counts = (int*)malloc(sizeof(int) * size);
MPI_Gather(&count, 1, MPI_INT, counts, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("素数:");
for (int i = 0; i < n / size * size; i++) {
int num;
scanf("%d", &num);
if (is_prime(num)) printf("%d ", num);
}
printf("\n");
}
free(nums);
free(counts);
MPI_Finalize();
return 0;
}
```
阅读全文