Advertisement
HasanRasulov

prime_in_range.cpp

Dec 27th, 2019
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include<iostream>
  2. #include<vector>
  3. #include<cmath>
  4. #include<cstring>
  5. using namespace std;
  6.  
  7.  
  8. void simpleSieve(int limit, vector<int>& prime)
  9. {
  10.     bool mark[limit + 1];
  11.     memset(mark, false, sizeof(mark));
  12.  
  13.     for (int i = 2; i <= limit; ++i) {
  14.         if (!mark[i]) {
  15.            
  16.             prime.push_back(i);
  17.             for (int j = i; j <= limit; j += i)
  18.                 mark[j] = true;
  19.         }
  20.     }
  21. }
  22.  
  23.  
  24. void primesInRange(int low, int high)
  25. {
  26.  
  27.  
  28.     int limit = floor(sqrt(high)) + 1;
  29.     vector<int> prime;
  30.     simpleSieve(limit, prime);
  31.  
  32.  
  33.     int n = high - low + 1;
  34.  
  35.  
  36.     bool mark[n + 1];
  37.     memset(mark, false, sizeof(mark));
  38.  
  39.    
  40.     for (int i = 0; i < prime.size(); i++) {
  41.        
  42.        
  43.         int loLim = floor(low / prime[i]) * prime[i];
  44.         if (loLim < low)
  45.             loLim += prime[i];
  46.         if(loLim==prime[i])
  47.             loLim += prime[i];
  48.        
  49.         for (int j = loLim; j <= high; j += prime[i])
  50.             mark[j - low] = true;
  51.     }
  52.  
  53.    
  54.     for (int i = low; i <= high; i++)
  55.         if (!mark[i - low])
  56.             cout << i << " ";
  57. }
  58.  
  59.  
  60. int main()
  61. {
  62.     int t;
  63.     std::cin >> t;
  64.     while (t--)
  65.     {
  66.         int n, m;
  67.         std::cin >> n;
  68.         std::cin >> m;
  69.         primesInRange(n==1?++n:n, m);
  70.         std::cout << std::endl;
  71.     }
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement