C++ 实现 Miller Rabin 算法
Miller Rabin 素性检验是一种常用的素数判定算法,不同于传统的试除法和反演数学方法。Miller Rabin 素性检验的本质是一种随机化算法,能够快速判断一个数是否为质数。
下面给出 C++ 实现的 Miller Rabin 算法代码,使用时只需将数字 n 和精度 k 传入函数 is_prime 即可。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef long long LL;
LL quick_mul(LL a, LL b, LL mod) {
LL res = 0;
while (b) {
if (b & 1) res = (res + a) % mod;
a = a * 2 % mod;
b >>= 1;
}
return res;
}
LL quick_pow(LL a, LL b, LL mod) {
LL res = 1;
while (b) {
if (b & 1) res = quick_mul(res, a, mod);
a = quick_mul(a, a, mod);
b >>