devdbi

erastotenes.c

Aug 13th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. /*
  2. * Adapted from: http://w...content-available-to-author-only...s.org/sieve-of-eratosthenes
  3. */
  4.  
  5.  
  6. /*
  7.  
  8. sequencial:
  9.  
  10. 5761455
  11.  
  12. real    0m4.053s
  13. user    0m3.977s
  14. sys 0m0.068s
  15.  
  16. paralelo:
  17.  
  18. 5761455
  19.  
  20. real    0m3.105s
  21. user    0m5.662s
  22. sys 0m0.072s
  23.  
  24. speedup user = 1,4166
  25.  
  26. */
  27.  
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <stdbool.h>
  31. #include <string.h>
  32. #include <math.h>
  33. #include <omp.h>
  34.  
  35. int sieveOfEratosthenes(int n)
  36. {
  37.    omp_set_num_threads(2);
  38.    // Create a boolean array "prime[0..n]" and initialize
  39.    // all entries it as true. A value in prime[i] will
  40.    // finally be false if i is Not a prime, else true.
  41.    int primes = 0;
  42.    bool *prime = (bool*) malloc((n+1)*sizeof(bool));
  43.    int sqrt_n = sqrt(n);
  44.    int nt = 0;
  45.  
  46.    memset(prime, true,(n+1)*sizeof(bool));
  47.  
  48.    for (int p=2; p <= sqrt_n; p++)
  49.    {
  50.        // If prime[p] is not changed, then it is a prime
  51.        if (prime[p] == true)
  52.        {
  53.            // Update all multiples of p
  54.            #pragma omp parallel for
  55.            for (int i=p*2; i<=n; i += p)
  56.                prime[i] = false;
  57.        }
  58.     }
  59.  
  60.     // count prime numbers
  61.     #pragma parallel for reduction(+:primes)
  62.     for (int p=2; p<=n; p++)
  63.        if (prime[p])
  64.          primes++;
  65.    
  66.     return(primes);
  67. }
  68.  
  69. int main()
  70. {
  71.    int n = 100000000;
  72.    printf("%d\n",sieveOfEratosthenes(n));
  73.    return 0;
  74. }
  75.  
Add Comment
Please, Sign In to add comment