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
题解:
直接暴力肯定会T,那就间接暴力呗。先找出从 a 到 b 之间的回文数,再在这些回文数里边找素数。
因为有些地方没处理好,所以在 b < 99999 的时候直接就暴力找回文数了......
代码如下: string 函数的用法
#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#define MAX 0x3f3f3f3f
using namespace std;
typedef long long LL;
int h[51111];
int str_int(string t) //string 转 int
{
int ans;
istringstream is(t);
is >> ans;
return ans;
}
void int_str(int i,string &s) //int 转 string
{
ostringstream os;
os << i;
s+=os.str();
}
int main()
{
int a,b,p=0,L;
string k;
cin >> a >> b;
if(b<99999)
L=b;
else
{
int m=sqrt(b+1),ll=1;
int_str(m,k);
for(int i=1; i<k.size(); i++)
ll*=10;
L=ll*(k[0]-'0'+1);
}
for(int i=1; i<=L; i++)
{
string t,s;
int_str(i,s);
t+=s;
int len=s.size();
reverse(s.begin(),s.end());
t+=s;
if(str_int(t)<=b&&str_int(t)>=a)
h[p++]=str_int(t);
for(char j='0'; j<='9'; j++)
{
t.erase(len); //删到从下标为len至结尾的字符
t+=j;
t+=s;
if(str_int(t)<=b&&str_int(t)>=a)
h[p++]=str_int(t);
}
if(i<10&&i>=a)
h[p++]=i;
}
sort(h,h+p);
int j;
for(int i=0; i<p; i++)
{
int m=sqrt(h[i])+1;
for(j=2; j<=m; j++)
{
if(h[i]%j==0)
break;
}
if(j>m)
cout << h[i] <<endl;
}
return 0;
}