题解:P16800 [蓝桥杯 2026 国 B] 方和质数
xiaowang_Duyea · · 题解
题目意思
题目要求:在
思路
- 遍历
x=L 到R 。 - 计算数位和
s 。 - 若
s 是完全平方数 且x 是质数→ 计数+1 。 - 计数到
K 则输出x 。 - 遍历完未找到输出
-1 。
这里我们可以注意到我们质数判定用寻常方法是行不通的,数组明显开不到那么大,我们可以用到一个叫做 Miller–Rabin 的质数判断算法。
简要介绍一下基本原理和核心的算法:
1. 费马小定理
若
逆否命题:若存在
但反之不成立。存在合数
2. 二次探测定理
若
的解只有
3. 算法核心
对于待测奇数
- 将
n-1 分解为n-1 = d \times 2^r ,其中d 为奇数 - 选取基底
a (如2, 3, 5, 7, 11, 13 ) - 计算
x = a^d \bmod n - 若
x \equiv 1 或x \equiv n-1 ,则本次测试通过 - 否则重复平方
r-1 次:x = x^2 \bmod n
若某次x \equiv n-1 ,则测试通过
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
// 快速幂取模
ll mulmod(ll a, ll b, ll mod) {
ll res = 0;
while (b) {
if (b & 1) res = (res + a) % mod;
a = (a + a) % mod;
b >>= 1;
}
return res;
}
ll powmod(ll a, ll d, ll mod) {
ll res = 1;
while (d) {
if (d & 1) res = mulmod(res, a, mod);
a = mulmod(a, a, mod);
d >>= 1;
}
return res;
}
// 确定性 Miller–Rabin 对于 ≤ 1e12
bool is_prime(ll n) {
if (n < 2) return false;
if (n == 2 || n == 3) return true;
if (n % 2 == 0) return false;
// 测试基底
ll base[] = {2, 3, 5, 7, 11, 13};
ll d = n - 1;
int r = 0;
while (d % 2 == 0) d /= 2, r++;
for (ll a : base) {
if (a % n == 0) continue;
ll x = powmod(a, d, n);
if (x == 1 || x == n - 1) continue;
bool comp = true;
for (int i = 0; i < r - 1; ++i) {
x = mulmod(x, x, n);
if (x == n - 1) {
comp = false;
break;
}
}
if (comp) return false;
}
return true;
}
int digit_sum(ll x) {
int s = 0;
while (x) {
s += x % 10;
x /= 10;
}
return s;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll L, R;
int K;
cin >> L >> R >> K;
// 完全平方数标记
bool sq[110] = {false};
for (int i = 1; i * i <= 108; ++i) sq[i * i] = true;
int cnt = 0;
for (ll x = L; x <= R; ++x) {
int sd = digit_sum(x);
if (sq[sd] && is_prime(x)) {
cnt++;
if (cnt == K) {
cout << x << "\n";
return 0;
}
}
}
cout << "-1\n";
return 0;
}
AC记录