Prime Palindromes
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
1
1 101
151
131 181
353
191 313 373
383
/*
ID:yfr_1992
PROG:pprime
LANG:C++
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
vector<int> plist;
int temp[10],sz;
void dfs(int cur,int limit){
if(cur>((limit-1)>>1)){
int sum = 0;
for(int i=0;i<limit;i++)sum = sum*10 + temp[i];
plist.push_back(sum);
return;
}
for(int i=0;i<10;i++){
temp[cur] = i,temp[limit-1-cur] = i;
dfs(cur+1,limit);
}
}
bool isPrime(int x){
for(int i=2;i<=(int)sqrt(x)+1;i++){
if((x%i)==0)return false;
}
return true;
}
int bs_lower(int x){
int l = 0, r = sz-1 , m ;
while(l<=r){
m = (l+r)>>1;
if(plist[m]>=x)r = m-1;
else l = m+1;
}
return l;
}
int bs_upper(int x){
int l = 0, r = sz-1 , m ;
while(l<=r){
m = (l+r)>>1;
if(plist[m]>x)r = m-1;
else l = m+1;
}
return r;
}
int main(){
freopen("pprime.in","r",stdin);
freopen("pprime.out","w",stdout);
for(int i=1;i<=8;i++)dfs(0,i);
sort(plist.begin(),plist.end());
sz = 1;
for(int i=1;i<(int)plist.size();i++){
if(plist[i]!=plist[i-1])plist[sz++] = plist[i];
}
int a,b;
scanf("%d%d",&a,&b);
int s = bs_lower(a), e = bs_upper(b);
for(int i=s;i<=e;i++){
if(isPrime(plist[i]))printf("%d\n",plist[i]);
}
return 0;
}