洛谷 B3939:[GESP样题 四级] 绝对素数 ← 素数判定+逆序整数
【题目来源】
https://www.luogu.com.cn/problem/B3939
【题目描述】
如果一个两位数是素数,且它的数字位置经过对换后仍为素数,则称为绝对素数,例如 13。给定两个正整数 A,B,请求出大于等于 A、小于等于 B 的所有绝对素数。
【输入格式】
输入 1 行,包含两个正整数 A 和 B。保证 10<A<B<100。
【输出格式】
若干行,每行一个绝对素数,从小到大输出。
【输入样例】
11 20
【输出样例】
11
13
17
【算法分析】
● 素数判定的经典代码:https://blog.csdn.net/hnjzsyjyj/article/details/148121301
bool isPrime(int n) {if(n<2) return false;for(int i=2; i*i<=n; i++) {if(n%i==0) return false;}return true;
}
● 逆序输出一个整数的代码
int revInt(int x) {int t=0;while(x!=0) {int rem=x%10;t=t*10+rem;x/=10;}return t;
}
【算法代码】
#include <bits/stdc++.h>
using namespace std;int revInt(int x) {int t=0;while(x!=0) {int rem=x%10;t=t*10+rem;x/=10;}return t;
}bool isPrime(int x) {if(x<2) return false;for(int i=2; i*i<=x; i++) {if(x%i==0) return false;}return true;
}int main() {int x,y;cin>>x>>y;for(int i=x; i<=y; i++) {int t=revInt(i);if(isPrime(i) && isPrime(t)) {cout<<i<<endl;}}return 0;
}/*
in:
11 20out:
11
13
17
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/148121301
https://blog.csdn.net/hnjzsyjyj/article/details/144323880