Advertisement
rajeshinternshala

Untitled

Oct 16th, 2023
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5. #include <omp.h>
  6.  
  7. #define N 1000000  // Change this value as needed
  8.  
  9. void sieve_recursive(char* sieve, int start, int end, int sqrtN) {
  10.     if (start > end) return;
  11.  
  12.     int middle = (start + end) / 2;
  13.    
  14.     #pragma omp task firstprivate(sieve, start, middle, sqrtN)
  15.     sieve_recursive(sieve, start, middle, sqrtN);
  16.  
  17.     #pragma omp task firstprivate(sieve, middle + 1, end, sqrtN)
  18.     sieve_recursive(sieve, middle + 1, end, sqrtN);
  19.  
  20.     #pragma omp taskwait
  21.  
  22.     for (int i = 2; i <= sqrtN; i++) {
  23.         if (sieve[i]) {
  24.             for (int j = fmax(i * i, (start + i - 1) / i * i); j <= end; j += i) {
  25.                 sieve[j] = 0;
  26.             }
  27.         }
  28.     }
  29. }
  30.  
  31. int main() {
  32.     int sqrtN = sqrt(N);
  33.     char* sieve = malloc(N);
  34.  
  35.     if (!sieve) {
  36.         fprintf(stderr, "Memory allocation failed for sieve of size %d\n", N);
  37.         return 1;
  38.     }
  39.     memset(sieve, 1, N);
  40.  
  41.     #pragma omp parallel
  42.     {
  43.         #pragma omp single nowait
  44.         {
  45.             sieve_recursive(sieve, 2, N - 1, sqrtN);
  46.         }
  47.     }
  48.  
  49.     // Print prime numbers
  50.     for (int i = 2; i < N; i++) {
  51.         if (sieve[i]) {
  52.             printf("%d ", i);
  53.         }
  54.     }
  55.     printf("\n");
  56.  
  57.     free(sieve);
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement