The number 151 is a prime palindrome because it is both a prime number and a palindrome (it is the same number when read forward as backward). Write a program that finds all prime palindromes in the range of two supplied numbers a and b (5 <= a < b <= 100,000,000); both a and b are considered to be within the range .
PROGRAM NAME: pprime
INPUT FORMAT
Line 1: | Two integers, a and b |
SAMPLE INPUT (file pprime.in)
5 500
OUTPUT FORMAT
The list of palindromic primes in numerical order, one per line.SAMPLE OUTPUT (file pprime.out)
5 7 11 101 131 151 181 191 313 353 373 383
写了好久最后看了提示才写出来......
这道题需要注意的地方:
1.求素数的时候只需要从2一直判断到n的开方就行了(如果这个有大于根号n的因子,那么另一个因子一定小于根号n)
2.偶数位数的回文一定能被11整除,因此只需要生成奇数位数的回文即可(11要特殊判断)
/*
ID:
PROG: pprime
LANG: C++
*/
#include<cstdio>
int a,b;
int tem;
int prime(int n){
for(int i=2;i*i<=n;i++){
if(n%i==0)return 0;
}
return 1;
}
int main(){
freopen("pprime.in","r",stdin);
freopen("pprime.out","w",stdout);
scanf("%d%d",&a,&b);
//5-11的即使素数又的回文数(12-99中是回文的数不是素数)
for(int i=5;i<=11;i++){
if(prime(i)&&i>=a&&i<=b)printf("%d\n",i);
}
for(int i1=0;i1<=9;i1++)
for(int i2=0;i2<=9;i2++)
for(int i3=0;i3<=9;i3++)
for(int i4=0;i4<=9;i4++)
for(int i5=0;i5<=9;i5++){
if(!i1&&!i2&&!i3)tem=101*i4+10*i5;//3位
else if(!i1&&!i2)tem=10001*i3+1010*i4+100*i5;//5位
else if(!i1)tem=1000001*i2+100010*i3+10100*i4+1000*i5;//7位
if(prime(tem)&&tem>=a&&tem<=b)printf("%d\n",tem);
}
}