Advertisement
vlatkovski

Efficient Sieve of Eratosthenes

Mar 10th, 2018
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. //https://www.geeksforgeeks.org/sieve-eratosthenes-0n-time-complexity/
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. const long long MAX_SIZE = 1000001;
  5.  
  6. // isPrime[] : isPrime[i] is true if number is prime
  7. // prime[] : stores all prime number less than N
  8. // SPF[] that store smallest prime factor of number
  9. // [for Exp : smallest prime factor of '8' and '16'
  10. // is '2' so we put SPF[8] = 2 , SPF[16] = 2 ]
  11. vector<long long >isprime(MAX_SIZE , true);
  12. vector<long long >prime;
  13. vector<long long >SPF(MAX_SIZE);
  14.  
  15. // function generate all prime number less then N in O(n)
  16. void manipulated_seive(int N)
  17. {
  18.     // 0 and 1 are not prime
  19.     isprime[0] = isprime[1] = false ;
  20.  
  21.     // Fill rest of the entries
  22.     for (long long int i=2; i<N ; i++)
  23.     {
  24.         // If isPrime[i] == True then i is
  25.         // prime number
  26.         if (isprime[i])
  27.         {
  28.             // put i into prime[] vector
  29.             prime.push_back(i);
  30.  
  31.             // A prime number is its own smallest
  32.             // prime factor
  33.             SPF[i] = i;
  34.         }
  35.  
  36.         // Remove all multiples of  i*prime[j] which are
  37.         // not prime by making isPrime[i*prime[j]] = false
  38.         // and put smallest prime factor of i*Prime[j] as prime[j]
  39.         // [ for exp :let  i = 5 , j = 0 , prime[j] = 2 [ i*prime[j] = 10 ]
  40.         // so smallest prime factor of '10' is '2' that is prime[j] ]
  41.         // this loop run only one time for number which are not prime
  42.         for (long long int j=0;
  43.              j < (int)prime.size() &&
  44.              i*prime[j] < N && prime[j] <= SPF[i];
  45.              j++)
  46.         {
  47.             isprime[i*prime[j]]=false;
  48.  
  49.             // put smallest prime factor of i*prime[j]
  50.             SPF[i*prime[j]] = prime[j] ;
  51.         }
  52.     }
  53. }
  54.  
  55. // driver  program to test above function
  56. int main()
  57. {
  58.     int N = 13 ; // Must be less than MAX_SIZE
  59.  
  60.     manipulated_seive(N);
  61.  
  62.     // pint all prime number less then N
  63.     for (int i=0; i<prime.size() && prime[i] <= N ; i++)
  64.         cout << prime[i] << " ";
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement