devdbi

Numbers primes in the range

May 7th, 2016
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <mpi.h>
  5.  
  6. /*******************************************
  7. Method to verify if number is prime
  8. ********************************************/
  9.  
  10. #define MASTER 0
  11.  
  12. int is_prime(long num){
  13.     long max_divisor, d;
  14.     if(num<=1)
  15.         return 0;
  16.     else if(num>3){
  17.         if(num%2==0)
  18.             return 0;
  19.         max_divisor = sqrt(num);
  20.         for(d = 3; d<=max_divisor; d+=2){
  21.             if(num%d==0) return 0;
  22.         }
  23.     }
  24.     return 1;
  25. }
  26.  
  27.  
  28. /*******************************************
  29. Main method
  30. ********************************************/
  31.  
  32. int main(int argc, char** argv)
  33. {
  34.     // proc
  35.     int quant = 1000, // num  
  36.         i,
  37.         localSum = 0,
  38.         globalSum = 0, tmp;
  39.  
  40.     // comm
  41.     int myrank, nprocs;
  42.  
  43.     // split
  44.     int split,
  45.         begin,
  46.         end;
  47.  
  48.     MPI_Init(&argc, &argv);
  49.     MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
  50.     MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
  51.  
  52.     // split tasks
  53.     split = ceil((float)(quant)/nprocs);
  54.     begin = split * myrank;
  55.     end = split * (myrank+1);
  56.  
  57.     // if happen overflow
  58.     if (end > quant)
  59.         end = quant;
  60.  
  61.     for (i = begin; i < end; ++i)
  62.     {
  63.         if (is_prime(i))
  64.             localSum++;
  65.     }
  66.     // receive all sums of others process
  67.     if (myrank == MASTER){
  68.         globalSum = localSum;
  69.         for (i = 0; i < nprocs; ++i)
  70.         {
  71.             MPI_Recv(&tmp,1,MPI_INT,i,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  72.             globalSum += tmp;
  73.         }
  74.         printf("%d primes were found between %d and %d\n", globalSum, 0, quant);
  75.     }
  76.     // send the local sum to master process
  77.     else{
  78.         MPI_Send(&localSum,1,MPI_INT,MASTER,0,MPI_COMM_WORLD); 
  79.     }
  80.  
  81.     MPI_Finalize();
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment