题目描述
解题思路
用素数筛法预处理,最后询问ans[r] - ans[l-1]即可.
参考代码
#include <stdio.h>
#include <string.h>
const int maxn = 1000010;
bool IsPrime[maxn];
int Prime[maxn/2];
int ans[maxn];
void GetPrime(){
int tot = 0;
memset(IsPrime,true,sizeof(IsPrime));
memset(ans,0,sizeof(ans));
for (int i = 2;i <= maxn;i++){
if (IsPrime[i]) Prime[tot++] = i;
for (int j = 0;j < tot;j++){
if (i*Prime[j] > maxn) break;
IsPrime[i*Prime[j]] = false;
if (i% Prime[j] == 0) break;
}
}
}
bool Check(int n){
int sum = 0;
while (n){
sum += (n%10);
n /= 10;
}
return IsPrime[sum];
}
int main()
{
int T;
GetPrime();
ans[0] = ans[1] = 0;
for (int i = 2;i < maxn;i++)
if (IsPrime[i] && Check(i))
ans[i] = ans[i-1]+1;
else ans[i] = ans[i-1];
while (~scanf("%d",&T)){
for (int i = 1;i <= T;i++){
int l,r;
scanf("%d %d",&l,&r);
printf("Case #%d: %d\n",i,ans[r]-ans[l-1]);
}
}
return 0;
}