题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1431
Problem Description
xiaoou33对既是素数又是回文的数特别感兴趣。比如说151既是素数又是个回文。现在xiaoou333想要你帮助他找出某个范围内的素数回文数,请你写个程序找出 a 跟b 之间满足条件的数。(5 <= a < b <= 100,000,000);
Input
这里有许多组数据,每组包括两组数据a跟b。
Output
对每一组数据,按从小到大输出a,b之间所有满足条件的素数回文数(包括a跟b)每组数据之后空一行。
Sample Input
5 500
Sample Output
5
7
11
101
131
151
181
191
313
353
373
383
题解: (参考自https://blog.youkuaiyun.com/Sentiment_logos/article/details/79073932)
因为要在大范围内查找素数,所以采用快速素数筛,回文数的话直接手动转置判断是否和原来的数相等就可以了。
因为给定的范围大,直接做会超时,所以先在本地算出结果观察规律。
最后发现1亿以内的回文素数最大为9989899,不到1千万,相当于9989899以后的数都不用判断了,瞬间数据规模就下降了一个指数级。
用flag数组来标记回文素数,先素数筛,false表示是素数,然后在素数中判断回文,如果不是回文,标记改为true.
这样flag数组中标记为false的就是回文素数。(当然也可以直接把本地跑出来的结果放在数组里打表)
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
bool flag[9989900];// false表示是素数
// 素数筛
void Init() {
memset(flag,0,sizeof(flag));
for(int i = 2;i <= 9989899;i++) {
if(flag[i] == false) {
for(int j = 2*i;j <= 9989899;j += i) {
flag[j] = true;
}
}
}
}
// 判断x是否是回文数
bool IsPalindrome(int x) {
int temp = x;
int ret = 0;
while(x) {
ret = ret * 10 + x % 10;
x /= 10;
}
if(ret == temp) return true;
return false;
}
int main()
{
Init();
for(int i = 1;i <= 9989899;i++) {
if(flag[i] == true)
continue;
if(!IsPalindrome(i))
flag[i] = true;
}
int a,b;
while(scanf("%d%d",&a,&b) != EOF) {
if(b > 9989899) b = 9989899;
for(int i = a;i <= b;i++) {
if(flag[i] == false)
printf("%d\n",i);
}
printf("\n");
}
return 0;
}