- Description
因为151既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数。
写一个程序来找出范围[a,b](5 <= a < b <= 100,000,000)( 一亿)间的所有回文质数;
- Input
多组输入数据
第 1 行: 二个整数 a 和 b .
- Output
输出一个回文质数的列表,一行一个。
- Sample Input
5 500
- Sample Output
5
7
11
101
131
151
181
191
313
353
373
383
int 1: Generate the palindromes and see if they are prime.
提示 1: 找出所有的回文数再判断它们是不是质数(素数).
Hint 2: Generate palindromes by combining digits properly. You might need more than one of the loops like below.
提示 2: 要产生正确的回文数,你可能需要几个像下面这样的循环。
题目翻译来自NOCOW。
USACO Training Section 1.5
产生长度为5的回文数:
#include<stdio.h>
#include<math.h>
int ans[1000],count=0;
int sushu(int a){//判断素数
int i;
for(i=2;i<=sqrt(a);i++){
if(a%i==0)return 0;
}
return 1;
}
int main(){
int a,b;
scanf("%d%d",&a,&b);
int i,a1,a2,a3,a4,flag=0,flag1=0;//flag判断是否大于b,flag1判断11是否添加过了
for(a1=0;a1<=9;a1++){
if(flag==1)break;
for(a2=0;a2<=9;a2++){
if(flag==1)break;
for(a3=0;a3<=9;a3++){
if(flag==1)break;
for(a4=0;a4<=9;a4++){
int temp;
if(a1){temp=a1*1000000+a2*100000+a3*10000+a4*1000+a3*100+a2*10+a1;}
else if(a2){temp=a2*10000+a3*1000+a4*100+a3*10+a2;}
else if(a3){
if(b>=11&&flag1==0){//将b添加到ans数组,注意限制条件,只添加一次
if(a<=11)
ans[count++]=11;
flag1=1;
}
temp=a3*100+a4*10+a3;}
else temp=a4;
if(temp>b){//如果大于b就退出循环
flag=1;
break;
}
else if(sushu(temp)&&temp>=a)//如果大于a且是素数就添加
ans[count++]=temp;
}
}
}
}
for(i=0;i<count;i++){
printf("%d\n",ans[i]);
}
}