Given integers a, b, how many prime numbers are in the interval [a, b)?
a<b<=10^12
b-a<=10^6
First think of violence, but if violence is judged simply, the time complexity is between O((ba)*a^(1/2))~O((ba)*b^(1/2)), which is probably O(10^12), the efficiency is too low, it must time out.
Think of the Ehrlich sieve method again, ans=sieve(b)-sieve(a), first type a 10^12 table, but the time complexity and space complexity both reach 10^12, which is still not enough.
But we know that the smallest prime factor of composite numbers within b does not exceed b^(1/2). If there is a table of prime numbers within b^(1/2) and a table of integers within [a, b), we can It is possible to sieve only the numbers in [a,b),
The time complexity is also close to ba, O(10^6), which can solve the problem
Code:
const int max_sqrt_b=1000000;
bool is_prime[1000005];
bool is_prime_small[max_sqrt_b];
// 对区间[a,b)内的整数实行筛法。is_prime[i-a]=true,i是素数
void segment_sieve(ll a,ll b){
for(int i=0;(ll)i*i<b;i++)is_prime_small[i]=true;
for(int i=0;(ll)i<b-a;i++)is_prime[i]=true;
for(int i=2;(ll)i*i<b;i++){
if(is_prime_small[i]){
for(int j=2*i;(ll)j*j<b;j+=i)is_prime_small[j]=false;
for(ll j=max(2LL,(a+i-1)/i)*i;(ll)j<b;j+=i)is_prime[j-a]=false;
}
}
}