Advertisement
Imran2544

Sieve of Eratosthenes

Sep 17th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long long pr[15001];
  5.  
  6. void SieveOfEratosthenes(long long n)
  7. {
  8.     // Create a boolean array "prime[0..n]" and initialize
  9.     // all entries it as true. A value in prime[i] will
  10.     // finally be false if i is Not a prime, else true.
  11.     bool prime[n+1];
  12.     memset(prime, true, sizeof(prime));
  13.  
  14.     for (long long p=2; p*p<=n; p++)
  15.     {
  16.         // If prime[p] is not changed, then it is a prime
  17.         if (prime[p] == true)
  18.         {
  19.             // Update all multiples of p
  20.             for (long long i=p*2; i<=n; i += p)
  21.                 prime[i] = false;
  22.         }
  23.     }
  24.  
  25.     //Storing all prime numbers in a single array
  26.     for (long long p=2, j=1; p<=n; p++)
  27.        if (prime[p]) {
  28.           pr[j]=p;
  29.           j++;
  30.        }
  31. }
  32.  
  33. // Driver Program to test above function
  34. int main()
  35. {
  36.     int t, n;
  37.     SieveOfEratosthenes(164000);
  38.     cin>>t;
  39.     while (t--) {
  40.         cin>>n;
  41.         cout<<pr[n]<<endl;
  42.     }
  43.     return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement