1. 回文质数
method 1(512ms):
/*回文质数
优化:偶数位的回文数整除11,故不为质数
*/
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int s, e;
void pre() {
int out[5] = { 2,3,5,7,11 };
for (int cnt = 0; cnt < 5; cnt++) {
if (out[cnt] >= s && out[cnt] <= e) {
cout << out[cnt] << '\n';
}
}
s = max(13, s);
if (s % 2 == 0) s += 1;
}
bool palin_odd_num(int &i) {
int out[8];
int cnt = 0;
int tmpi = i;
int mul = 1;
bool flag = true;
while (tmpi) {
out[cnt] = tmpi % 10;
tmpi /= 10;
mul *= 10;
cnt++;
}
if (cnt % 2 == 0) {
i = mul - 1; //当前位数的最后一位
flag = false;
}
else {
for (int i = 0; i < cnt / 2; i++) {
if (out[i] != out[cnt - i - 1]) {
flag = false;
break;
}
}
}
return flag;
}
bool prime(int i) { //适用:i>=2
int level = (int)sqrt(i);
bool flag = true;
for (int j = 2; j <= level; j++) {
if (i % j == 0) {
flag = false;
break;
}
}
return flag;
}
void solve() {
pre();
for (int i = s; i <= e; i+=2) { //只考虑奇数部分
if (palin_odd_num(i) && prime(i)) cout << i << '\n';
}
}
int main() {
cin >> s >> e;
solve();
return 0;
}
method 2(12ms):
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int s, e;
void pre() {
int out[5] = { 2,3,5,7,11 };
for (int cnt = 0; cnt < 5; cnt++) {
if (out[cnt] >= s && out[cnt] <= e) {
cout << out[cnt] << '\n';
}
}
}
int getbits(int num) {
int cnt = 0;
while (num) {
num /= 10;
cnt++;
}
return cnt;
}
int getv(int *bits, int bit) {
int v = 0;
//[abcd(e)]dcba
for (int i = 1; i <= bit; i++) {
v = v * 10 + bits[i];
}
for (int i = bit-1; i >= 1; i--) {
v = v * 10 + bits[i];
}
return v;
}
bool prime(int i) { //适用:i>=2
int level = (int)sqrt(i);
bool flag = true;
for (int j = 2; j <= level; j++) {
if (i % j == 0) {
flag = false;
break;
}
}
return flag;
}
void dfs(int i, int tmpbit, int bit, int *bits) {
if (tmpbit == bit) {
int v = getv(bits, bit);
if (v >= s && v <= e && prime(v)) cout << v << '\n';
return;
}
for (int k = 0; k <= 9; k++) { //0~9
bits[tmpbit+1] = k;
dfs(k, tmpbit + 1, bit, bits);
}
}
void solve() {
pre(); //处理位数为1、2的情况
int bits[5]; //奇数位最大为7-->(7+1)/2
int s_bit = getbits(s);
int e_bit = getbits(e);
if (s_bit == 1) s_bit = 3; //
if (e_bit == 9) e_bit = 7;
for (int bit = (s_bit % 2) ? s_bit : (s_bit + 1); bit <= e_bit; bit+=2) { //去掉偶数位
for (int i = 1; i <= 9; i += 2) { //首位数字为奇数
bits[1] = i;
dfs(i, 1, (bit + 1) / 2, bits);
}
}
}
int main() {
cin >> s >> e;
solve();
return 0;
}
method 3:
打表。。。万不得已简单快捷的方法
参照:
【1】回文质数:https://blog.csdn.net/a1033025319/article/details/46969809