打印n位回文素数,重点:不遍历构建n位回文数,参考博客
#include<stdio.h>
#include<math.h>
int hw(int x){ //如x=123,返回12321这样一个回文数
int ans=x;
x=x/10;
while(x>0){
ans=ans*10+x%10;
x/=10;
}
return ans;
}
bool is_prime(int x){
if(x%2==0) return 0;
for(int i=3;i*i<=x;i+=2)
if(x%i==0) return 0;
return 1;
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
if(n==1) printf("4\n2 3 5 7\n");
else if(n==2) printf("1\n11\n");
else if(n%2==0) printf("0\n");
else{
n=(n+1)/2;
int cnt=0,a=pow(10,n-1),b=pow(10,n),res[10000];
for(int i=a;i<b;i++){ //构造[a,b)区间内的回文数
int t=hw(i);
if(is_prime(t)) res[cnt++]=t;
}
printf("%d\n",cnt);
for(int i=0;i<cnt;i++)
printf("%d ",res[i]);
printf("\n");
}
}
}