SHARE
TWEET

Untitled

a guest Mar 26th, 2020 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <mpi.h>
  5.  
  6. #define N 100000
  7.  
  8. int k, size;
  9.  
  10. int is_prime(int n) {
  11.     if (n < 2) return 0;
  12.     if (n == 2) return 1;
  13.  
  14.     int m = 2;
  15.  
  16.     while (m < n) {
  17.         if (n % m == 0) return 0;
  18.         ++m;
  19.     }
  20.  
  21.     return 1;
  22. }
  23.  
  24. int get_idx_by_number(int n) {
  25.     int a = (n - 3) / 2;
  26.     return (a % size) * k + a / size;
  27. }
  28.  
  29. int main(int argc, char** argv) {
  30.     MPI_Status status;
  31.     int rank;
  32.  
  33.     MPI_Init(&argc, &argv);
  34.  
  35.     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  36.     MPI_Comm_size(MPI_COMM_WORLD, &size);
  37.  
  38.     int global_arr_size = (int) ceil((double)N / 2.0) - 1;
  39.     int local_arr_size = (int) ceil((double)global_arr_size / (double)size);
  40.     int *global_arr = (int *) calloc(global_arr_size, sizeof(int));
  41.     int *local_arr = (int *) calloc(local_arr_size, sizeof(int));
  42.    
  43.     k = local_arr_size;
  44.  
  45.     // Odredjuje da li su neparni brojevi od 3 do N prosti i rezultat cuva u global_arr
  46.     // Rezultat cuvam da se ne bi ponavljala provera da li je broj prost
  47.     int j = 0;
  48.     for (int i = rank + 1; i < N / 2; i += size) {
  49.         local_arr[j] = is_prime((2 * i) + 1);
  50.         j++;
  51.     }
  52.  
  53.     MPI_Allgather(local_arr, local_arr_size, MPI_INT, global_arr, local_arr_size, MPI_INT, MPI_COMM_WORLD);
  54.  
  55.     // Broji koliko parova susednih neparnih prostih brojeva ima od 3 do N
  56.     int local_count = 0;
  57.     for (int i = rank + 1; i < N / 2 - 1; i += size) {
  58.         if (global_arr[get_idx_by_number(2 * i + 1)]
  59.             && global_arr[get_idx_by_number(2 * (i + 1) + 1)]) {
  60.             ++local_count;
  61.         }
  62.     }
  63.  
  64.     int global_count;
  65.     MPI_Reduce(&local_count, &global_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
  66.  
  67.     if (rank == 0) {
  68.         printf("%d\n", global_count);
  69.     }
  70.  
  71.     MPI_Finalize();
  72. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top