/// Using Segmented Sieve to find Primes within a range (l..r)
/// Constaints: 1<=l<=r<=10^12, r-l<=10^6
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <bitset>
using namespace std;
#define ll long long
#define llu unsigned long long
#define endl "
"
#define pb push_back
#define N 1000000
typedef vector <ll> vi;
bitset < N + 1 > numbers;
vi primes;
void sieve(){
numbers.set();
numbers[1] = 0;
for (ll i = 2; i<N; i++){
if (numbers[i] == 1){
primes.pb(i);
for (ll j = i*i; j<N; j+=i){
numbers[j] = 0;
}
}
}
}
int main(){
sieve();
ll t;
cin>>t;
while (t--){
ll l,r;
cin>>l>>r;
float tmpSqrt = sqrt(r);
ll sqrtR = (ll)tmpSqrt;
if (tmpSqrt != (float)sqrtR)
sqrtR++;
ll lastPrimeIndexInRange = 0;
while (primes[lastPrimeIndexInRange] <= sqrtR)
lastPrimeIndexInRange++;
numbers.set();
if (l == 1)
numbers[0] = 0;
for (llu i = 0; i<lastPrimeIndexInRange; i++){
ll firstMulti = (l/primes[i]) * primes[i];
if (firstMulti < l)
firstMulti += primes[i];
for (ll j = max(firstMulti, primes[i] * primes[i]); j<=r; j+= primes[i])
numbers[j-l] = 0;
}
for (ll i = 0; i<r-l+1; i++)
if (numbers[i] == 1)
cout<<i + l<<endl;
cout<<endl;
}
return 0;
}
Code Example |
---|
Cpp :: segmented sieve cpp |
Cpp :: c++ cout colored output xcode |
Cpp :: C++ std::string find and replace |
Cpp :: string to decimal c++ strtol |
Cpp :: c++ factorial |
Cpp :: c++ inline in .cpp and not in header |
Cpp :: char ascii c++ |
Cpp :: convert integer to string c++ |
Cpp :: print 2d array c++ |
Cpp :: glew32.dll was not found |
Cpp :: iterate vector in reverse c++ |
Cpp :: read and write file in c++ |
Cpp :: continue c++ |
Cpp :: reverse function in cpp string |
Cpp :: how to find the sum of a vector c++ |
Cpp :: c++ how to add something at the start of a vector |
Cpp :: cpp get last element of vector |
Cpp :: find prime number c++ |
Cpp :: how to check a number in string |
Cpp :: c++ average |
Cpp :: bee 1002 solution |
Cpp :: json::iterator c++ |
Cpp :: sort array c++ |
Cpp :: c ifdef |
Cpp :: insertion sort cpp |
Cpp :: c++ random generator |
Cpp :: vector library c++ |
Cpp :: std::count() in C++ STL |
Cpp :: how to create a file in c++ |
Cpp :: how to find even and odd numbers in c++ |