题解
2025-06-13 19:33:41
发布于:浙江
0阅读
0回复
0点赞
使用了 Miller-Rabin 素数判定算法
#include <bits/stdc++.h>
using namespace std;
// 快速幂取模 (a^b mod n)
long long power_mod(long long a, long long b, long long n) {
long long res = 1;
a = a % n;
while (b > 0) {
if (b & 1) res = (res * a) % n;
b = b >> 1;
a = (a * a) % n;
}
return res;
}
// Miller-Rabin 检测核心
bool miller_test(long long d, long long n) {
long long a = 2 + rand() % (n - 4); // 随机基数 [2, n-2]
long long x = power_mod(a, d, n);
if (x == 1 || x == n - 1) return true;
while (d != n - 1) {
x = (x * x) % n;
d *= 2;
if (x == 1) return false;
if (x == n - 1) return true;
}
return false;
}
// 主函数:k为检测迭代次数(默认5次)
bool is_prime(long long n, int k = 5) {
if (n <= 1 || n == 4) return false;
if (n <= 3) return true;
long long d = n - 1;
while (d % 2 == 0) d /= 2; // 分解 n-1 = 2^s * d
for (int i = 0; i < k; i++) {
if (!miller_test(d, n)) return false;
}
return true;
}
int main() {
srand(time(0)); // 初始化随机种子
long long num;
cin >> num;
cout << (is_prime(num) ? "Yes":"No") << endl;
return 0;
}
这里空空如也
有帮助,赞一个