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
|
这个题目,如果范围比较小,判断是否素数,判断是否回文,两个函数+1个主程序里面的for循环就搞定。
但是 这个需要判断到100,000,000 == 1亿!!而且这个题目让人难受的是 需要先自己打表,这样才知道最大的回文素数是9989899。所以说感觉缺少条件,需要自己先探索,然后为了满足内存和时间要求再做题,真让人难受,我不喜欢。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
#include <stack>
using namespace std;
bool judge[10000001];//判断 0- 1000W之间 谁是素数 //bool 1个字节,int 4个字节
int prime[100000]; //存放素数
int cnt = 0;
bool isHuiwen(int n) {
//简单的栈 存放各个位数
int temp[10];
int cnt = 0;
//存入temp数组
while(n > 0) {
temp[cnt++] = n % 10;
n /= 10;
}
//检测是否回文,maxIndex 最大下标:若5位数,处理完cnt = 5, 存储范围 0 - 4,
int maxIndex = cnt - 1;
for (int i = 0; i <= cnt / 2; i++) {
if (temp[i] != temp[maxIndex - i]) {
return false;
}
}
return true;
}
//打表
void initial(int bound) {
//01不是素数
judge[0] = 0;
judge[1] = 0;
//初始化 , 默认全是素数
for (int i = 2; i <= bound; i++) {
judge[i] = 1;
}
//素数的倍数全都不是素数,从2开始标注2-4-6....,遇到下一个数3肯定是素数,标注3的倍数,打出素数表
for (int i = 2; i <= bound; i++) {
if(judge[i] == 1) {
for (int j = 2 * i; j <= bound; j += i) {
judge[j] = 0;
}
}
}
}
int main() {
int a, b;
cin >> a >> b;
initial(10000000);
for (int i = a; i <= b && i <= 10000000; i++) {
if (judge[i] && isHuiwen(i)) {
cout << i << endl;
}
}
cout << endl;
}