HDU 4548 美素数
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4548
中文题。
直接计数会超时,先素数打表+预处理,解决之。时间效率还好,在HDU上跑了15MS;
AC代码:
#include<stdio.h>
#include<string.h>
const int maxn=1000200;
bool prm[maxn];
int ans[maxn];
void getprm()
{
int i,j;
memset(prm,true,sizeof prm);
prm[0]=prm[1]=false;
for(i=2;i*i<maxn;i++)
{
if(prm[i])
{
for(j=i+i;j<maxn;j+=i)
{
prm[j]=false;
}
}
}
}
bool find(int n)
{
int m=n,sum;
sum=0;
while(m)
{
sum+=m%10;
m/=10;
}
return prm[sum];
}
int main()
{
int count,m;
int t,l,r,i;
getprm();//筛选法求素数;
for(i=0;i<=maxn;i++)//预处理出每个数之前的“美素数”,
{
if(prm[i] && find(i))
count++;
ans[i]=count;
}
while(scanf("%d",&t)!=EOF)
{
m=1;
while(t--)
{
count=0;
scanf("%d %d",&l,&r);
printf("Case #%d: ",m++);
printf("%d\n",ans[r]-ans[l-1]);
}
}
return 0;
}