Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <mpi.h>
- /*******************************************
- Method to verify if number is prime
- ********************************************/
- #define MASTER 0
- int is_prime(long num){
- long max_divisor, d;
- if(num<=1)
- return 0;
- else if(num>3){
- if(num%2==0)
- return 0;
- max_divisor = sqrt(num);
- for(d = 3; d<=max_divisor; d+=2){
- if(num%d==0) return 0;
- }
- }
- return 1;
- }
- /*******************************************
- Main method
- ********************************************/
- int main(int argc, char** argv)
- {
- // proc
- int quant = 1000, // num
- i,
- localSum = 0,
- globalSum = 0, tmp;
- // comm
- int myrank, nprocs;
- // split
- int split,
- begin,
- end;
- MPI_Init(&argc, &argv);
- MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
- MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
- // split tasks
- split = ceil((float)(quant)/nprocs);
- begin = split * myrank;
- end = split * (myrank+1);
- // if happen overflow
- if (end > quant)
- end = quant;
- for (i = begin; i < end; ++i)
- {
- if (is_prime(i))
- localSum++;
- }
- // receive all sums of others process
- if (myrank == MASTER){
- globalSum = localSum;
- for (i = 0; i < nprocs; ++i)
- {
- MPI_Recv(&tmp,1,MPI_INT,i,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
- globalSum += tmp;
- }
- printf("%d primes were found between %d and %d\n", globalSum, 0, quant);
- }
- // send the local sum to master process
- else{
- MPI_Send(&localSum,1,MPI_INT,MASTER,0,MPI_COMM_WORLD);
- }
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment