Prime Palindromes
Time limit : 15 s | Memory limit : 32 mb |
---|
Problem Description
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 <= 1000,000,000); both a and b are considered to be within the range .
Input
Line 1: Two integers, a and b
Output
The list of palindromic primes in numerical order, one per line.
Sample Input
5 500
Sample Output
5 7 11 101 131 151 181 191 313 353 373 383
心路历程:时间只给15秒,判断两次会超时,可以打表过。上课yogurt学长介绍了另一种方法,先创造回文数,再判断这个回文数是不是素数。
ac代码如下:
#include <cstdio>
#include <cstring>
#include <iostream>
#define ll long long
using namespace std;
int a,b;
//创造回文数,可以证明除11以外的偶数位回文数都为合数,所以只需特判11,并构造奇数位回文数
ll get(int val){
if(val==8) return 11;
int tmp=val;
tmp/=10;
while(tmp){
val=val*10+tmp%10;
tmp/=10;
}
return val;
}
//检查是不是素数
int check(int val)
{
if(val%2==0) return 0;
for(int i=3;i*i<=val;i+=2) if(val%i==0)return 0;
return 1;
}
int main()
{
while(~scanf("%d%d",&a,&b)){
int i;
for(i=1;i<=100000;i++){
ll tmp=get(i);
if(check(tmp)&&tmp>=a&&tmp<=b) printf("%d\n",tmp);
}
}
return 0;
}