原理:将1~10000的数轮流分配给各个进程检查是否为素数,并返回给主进程输出。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <mpi.h> /* For MPI functions, etc */
#include <math.h>
void Read_n(int* n_p, int my_rank, int comm_sz, MPI_Comm comm);
void Print_primes(short local_states[], int local_n, int n, int my_rank, MPI_Comm comm);
void Parallel_compute_primes(int my_rank, int comm_sz, int n, short* prime_states);
void Allocate_states(short** local_states, int local_n, MPI_Comm comm);
short Check_prime(int n);
int main(void) {
int n; /* Range of number */
int comm_sz; /* Number of processes */
int my_rank; /* My process rank */
int local_n; /* Number for each process*/
short *local_states; /* Output of every process*/
MPI_Comm comm;
/* Start up MPI */
MPI_Init(NULL, NULL);
comm = MPI_COMM_WORLD;
/* Get the number of processes */
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
/* Get my rank among all the processes */
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
Read_n(&n,my_rank,comm_sz,comm);
local_n = n/comm_sz;
Allocate_states(&local_states, local_n, comm); /*Allocate the states pointer for every process*/
Parallel_compute_primes(my_rank, comm_sz, n, local_states);
Print_primes(local_states, local_n, n, my_rank, comm);
/* Shut down MPI */
MPI_Finalize();
return 0;
} /* main */
void Read_n(
int* n_p,
int my_rank,
int comm_sz,
MPI_Comm comm){
if (my_rank==0){
printf("How many integers you want to check for primitivity?\n");
scanf("%d",n_p);
}
MPI_Bcast(n_p,1,MPI_INT,0,comm);/* Broadcast will be used by every process*/
}
void Allocate_states(
short** local_states,
int local_n,
MPI_Comm comm){
*local_states = malloc(local_n*sizeof(short));
}
void Parallel_compute_primes(
int my_rank,
int comm_sz,
int n,
short* prime_states){
int local_i;
int local_n = n/comm_sz;
for(local_i = 0; local_i < local_n; local_i ++){
prime_states[local_i] = Check_prime(my_rank + local_i*comm_sz + 1);
}
}
short Check_prime(int n){
if(n == 1) return (short)1;
if(n == 2) return (short)1;
double sqn = sqrt((double)n);
for(int i = 2; i <= sqn; i++){
if(n%i==0) return (short)0;
}
return (short)1;
}
void Print_primes(
short local_states[],
int local_n,
int n,
int my_rank,
MPI_Comm comm){
short* states = NULL;
if(my_rank==0){
int i, j;
int comm_sz = (int)(n/local_n);
states = malloc(n*sizeof(short));
MPI_Gather(local_states, local_n, MPI_SHORT, states, local_n, MPI_SHORT, 0, comm);
for(i = 0; i < local_n; i++)
for(j=0; j< comm_sz; j++)
if(states[i+j*local_n]==1)
printf("Found a prime: %d\n", i*comm_sz+j+1);
free(states);
}else{
MPI_Gather(local_states,local_n, MPI_SHORT, states, local_n, MPI_SHORT, 0, comm);
}
}
运行效果: