Almost prime numbers are the non-prime numbers which are divisible by
only a single prime number. In this problem your job is to write a
program which nds out the number of almost prime numbers within a
certain range. Input First line of the input le contains an integer N
( N 600) which indicates how many sets of inputs are there. Each of
the next N lines make a single set of input. Each set contains two
integer numbers low and high (0 < low high < 10 12 ). Output For
each line of input except the rst line you should produce one line of
output. This line contains a single integer, which indicates how many
almost prime numbers are within the range (inclusive) low : : : high .
先打出来sqrt(n)以内的素数表,然后对于每个素数x,他对答案的贡献就是最大的p使x^p<=n,即log(x,n)。注意精度误差。
用1..r的减去1..l-1的就是答案。
#include<cstdio>
#include<cstring>
#include<cmath>
#define LL long long
int prm[1000010],tot;
bool have[1000010];
LL qry(LL n)
{
LL ans=0;
for (int i=1;i<=tot&&(LL)prm[i]*prm[i]<=n;i++)
ans+=log(n+0.1)/log(prm[i])-1;
return ans;
}
int main()
{
int i,j,k,m,n,p,q,x,y,z,T;
LL l,r;
for (i=2;i<=1000000;i++)
{
if (!have[i]) prm[++tot]=i;
for (j=1;j<=tot&&i*prm[j]<=1000000;j++)
{
have[i*prm[j]]=1;
if (i%prm[j]==0) break;
}
}
scanf("%d",&T);
while (T--)
{
scanf("%lld%lld",&l,&r);
printf("%lld\n",qry(r)-qry(l-1));
}
}