博客
关于我
快速幂算法介绍
阅读量:243 次
发布时间:2019-03-01

本文共 831 字,大约阅读时间需要 2 分钟。

快速幂算法及其优化

快速幂是一种高效计算数的幂次的方法,避免了传统方法中重复乘法的低效性。通过将指数n分解为二进制形式,快速幂可以在O(log n)的时间复杂度内完成计算。

递归实现

int qpow(int a, int n) {    if (n == 0)        return 1;    else if (n % 2 == 1)        return qpow(a, n - 1) * a;    else {        int temp = qpow(a, n / 2);        return temp * temp;    }}

非递归实现

int qpow(int a, int n) {    int ans = 1;    while (n) {        if (n & 1) {            ans *= a;        }        a *= a;        n >>= 1;    }    return ans;}

快速幂取模优化

为了应对大数计算中的性能问题,快速幂通常结合取模操作。以下是对大素数取模的快速幂实现:

#define MOD 1000000007typedef long long ll;ll qpow(ll a, ll n) {    if (n == 0)        return 1;    else if (n % 2 == 1)        return qpow(a, n - 1) * a % MOD;    else {        ll temp = qpow(a, n / 2) % MOD;        return temp * temp % MOD;    }}

快速幂算法通过将指数二进制分解,减少了计算量。其递归和非递归实现均能显著提升效率,适用于大数运算。通过取模优化,可以进一步处理大素数问题,确保计算结果在可控范围内。

转载地址:http://xsmv.baihongyu.com/

你可能感兴趣的文章
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>