# 素数回文

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4276    Accepted Submission(s): 984

Problem Description
xiaoou33对既是素数又是回文的数特别感兴趣。比如说151既是素数又是个回文。现在xiaoou333想要你帮助他找出某个范围内的素数回文数，请你写个程序找出 a 跟b 之间满足条件的数。(5 <= a < b <= 100,000,000);

Input

Output

Sample Input
5 500

Sample Output
5 7 11 101 131 151 181 191 313 353 373 383

Author
xiaoou333

Source

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>

using namespace std;

int ans[20000],len=0;
int temp[20];

int change(int dep,int dk)
{
int i,ret=0;
if(dk==0)
{
for(i=1;i<=dep;i++)
ret=ret*10+temp[i];
for(i=dep;i>=1;i--)
ret=ret*10+temp[i];
}
else
{
for(i=1;i<dep;i++)
ret=ret*10+temp[i];
ret=ret*10+temp[dep];
for(i=dep-1;i>=1;i--)
ret=ret*10+temp[i];
}
return ret;
}

bool judge(int x)
{
int i;
if(x<=1)
return false;
for(i=2;i*i<=x;i++)
if(x%i==0)
return false;
return true;
}

void dfs(int id,int dep,int dk)
{
int i;
if(id>dep)
{
int x=change(dep,dk);
if(judge(x))
ans[len++]=x;
return;
}
for(i=0;i<=9;i++)
{
if(id==1&&i==0)
continue;
temp[id]=i;
dfs(id+1,dep,dk);
}
}

void init()
{
int l,k;
ans[len++]=2;
ans[len++]=3;
ans[len++]=5;
ans[len++]=7;
for(l=2;l<=9;l++)
{
k=(l+1)/2;
if(l&1)
dfs(1,k,1);
else
dfs(1,k,0);
}
}

int main()
{
int i;
init();
int a,b,x,y;
while(scanf("%d%d",&a,&b)!=EOF)
{
x=upper_bound(ans,ans+len,a)-ans;
y=upper_bound(ans,ans+len,b)-ans;
for(i=x-1;i<=y-1;i++)
printf("%d\n",ans[i]);
printf("\n");
}
return 0;
}

• 评论

1

• 下一篇
• 上一篇