本题最容易犯的错误是超时。这个方法可有效避免超时,31ms ac哦。
应用素数打表,然后再次对美素数打表,用一个数组存储从0—1000000分别拥有的美素数和。
随后要做的就是用这个负责存储的数组,在给定区间上做减法。
#include<stdio.h>
#include<math.h>
bool su[1000001],sum[1000001];
int b[1000001];
void nud() {
int t,n;
for(int l=2; l<1000001; l++) {
if(!su[l])
for(int j=l*2; j<1000001; j+=l)
su[j]=true;
}
su[0]=su[1]=true;
for(int l=0; l<1000001; l++) {
t=0;
if(!su[l]) {
n=l;
while(n) {
t+=n%10;
n/=10;
}
if(!su[t])
sum[l]=true;
}
}
n=0;
for(int l=0; l<1000001; l++) {
if(sum[l])
n++;
b[l]=n;
}
}
int main() {
int T,p=0,x,y;
nud();
scanf("%d",&T);
while(T--) {
scanf("%d %d",&x,&y);
printf("Case #%d: %d\n",++p,b[y]-b[x-1]);
}
return 0;
}

本文介绍了一种解决HOJ4548美素数问题的有效方法,通过预先计算并存储美素数的累积和,实现了快速查询指定区间内美素数的数量,有效避免了超时问题。
2013

被折叠的 条评论
为什么被折叠?



