C++ 实现 Miller Rabin 算法

189 篇文章 ¥59.90 ¥99.00
本文介绍了 Miller Rabin 素性检验算法,一种快速的随机化素数判定方法,时间复杂度为 O(klog3n)。提供了 C++ 代码实现,并指出取 k=10 可获得较高正确率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 >>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值