从 11 到 n 枚举每个整数,先判回文再判素数,统计两条件都满足的个数。
OJ: roj
题目 ID: 1408
难度:入门
标签:质数判定枚举回文数
创建: 2026-09-30 09:04
更新: 2026-10-05 23:11
题目描述
求
思路
数据范围很小,直接枚举
参考代码
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-09-30 09:06
# update_at: 2026-09-30 09:06
import sys
from math import isqrt
def is_prime(x: int) -> bool:
"""试除法判素数:只要 2 ~ √x 里没有因子就是素数。"""
return x >= 2 and all(x % d for d in range(2, isqrt(x) + 1))
def is_palindrome(x: int) -> bool:
"""回文判断:十进制表示正读反读一致。"""
s = str(x)
return s == s[::-1]
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
n = next(data)
# 11 到 n 逐个检查:先滤回文(便宜),幸存者再滤素数(试除),
# 两个条件都满足才计数;两位回文数都是 11 的倍数,幸存者极少
print(sum(1 for i in range(11, n + 1) if is_palindrome(i) and is_prime(i)))
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-04 22:12
* update_at: 2026-10-05 23:11
*/
#include <iostream>
using namespace std;
typedef long long ll;
// 判断 x 是否为回文数:十进制表示左右对称
bool is_palindrome(ll x) {
ll rev = 0, t = x;
while (t > 0) {
rev = rev * 10 + t % 10;
t /= 10;
}
return rev == x;
}
// 判断 x 是否为素数:试除到 sqrt(x)
bool is_prime(ll x) {
if (x < 2) return false;
for (ll i = 2; i * i <= x; ++i)
if (x % i == 0) return false;
return true;
}
ll n;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
ll ans = 0;
// 先判回文(快且筛掉多数),再判素数
for (ll i = 11; i <= n; ++i)
if (is_palindrome(i) && is_prime(i)) ++ans;
cout << ans << '\n';
return 0;
}