/// 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 :: primes in range cpp |
Cpp :: less than operator overloading in c++ |
Cpp :: max_element c++ |
Cpp :: string iterator in c++ |
Cpp :: read comma separated text file in c++ |
Cpp :: why are inline keyword in header c++ |
Cpp :: c++ greatest common divisor |
Cpp :: how to erase a certain value from a vector in C++ |
Cpp :: convert string to lpwstr |
Cpp :: int to hex arduino |
Cpp :: sort a 2d vector c++ stl |
Cpp :: 1523. Count Odd Numbers in an Interval Range solution in c++ |
Cpp :: C++ structure (Struct) |
Cpp :: c++ int |
Cpp :: c++ string to char array |
Cpp :: cpp pushfront vector |
Cpp :: use uint in c++ |
Cpp :: sqrt in c++ |
Cpp :: sorting using comparator in c++ |
Cpp :: c++ pass array to a function |
Cpp :: how to square a number in c++ |
Cpp :: classes and objects in c++ |
Cpp :: card validator c++ |
Cpp :: c #define |
Cpp :: opengl draw semi circle c++ |
Cpp :: array length c++ |
Cpp :: vector c++ |
Cpp :: c++ for loop multiple variables |
Cpp :: set size in c++ |
Cpp :: c++ integer array |