枚举所有两位数,输出自身与十位个位对换后均为素数的数。
OJ: roj
题目 ID: 1153
难度:入门
标签:素数枚举
创建: 2025-01-12 11:47
更新: 2026-10-05 03:44
题目描述
一个自然数是素数,且它的十位与个位对换后仍是素数,则称为绝对素数。求所有二位绝对素数,按从小到大顺序输出,每个数占一行。
思路
枚举
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-07-05 21:47
# update_at: 2026-07-05 21:47
import math
def is_prime(n: int) -> bool:
"""判断 n 是否为素数。"""
if n < 2:
return False
for i in range(2, int(math.isqrt(n)) + 1):
if n % i == 0:
return False
return True
def solve() -> None:
out: list[str] = []
for x in range(10, 100):
rev = x % 10 * 10 + x // 10 # 数字位置对换
if is_prime(x) and is_prime(rev):
out.append(str(x))
print('\n'.join(out))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 03:44
* update_at: 2026-10-05 03:44
*/
#include <cstdio>
using namespace std;
typedef long long ll;
// 判断 n 是否为素数
bool is_prime(ll n) {
if (n < 2) return false;
for (ll i = 2; i * i <= n; ++i) {
if (n % i == 0) return false;
}
return true;
}
int main() {
// 枚举所有两位数,若自身与十位个位对换后均为素数则输出
for (ll x = 10; x <= 99; ++x) {
ll rev = (x % 10) * 10 + (x / 10);
if (is_prime(x) && is_prime(rev)) {
printf("%lld\n", x);
}
}
return 0;
}