博客
关于我
快速幂算法介绍
阅读量: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/

你可能感兴趣的文章
Qt笔记——标准文件对话框QFileDialog
查看>>
poj 3083 Children of the Candy Corn
查看>>
POJ 3083 Children of the Candy Corn 解题报告
查看>>
POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
查看>>
Qt笔记——控件总结
查看>>
poj 3262 Protecting the Flowers 贪心
查看>>
poj 3264(简单线段树)
查看>>
Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
查看>>
poj 3277 线段树
查看>>
POJ 3349 Snowflake Snow Snowflakes
查看>>
POJ 3411 DFS
查看>>
poj 3422 Kaka's Matrix Travels (费用流 + 拆点)
查看>>
Qt笔记——官方文档全局定义(二)Functions函数
查看>>
POJ 3468 A Simple Problem with Integers
查看>>
poj 3468 A Simple Problem with Integers 降维线段树
查看>>
poj 3468 A Simple Problem with Integers(线段树 插线问线)
查看>>
poj 3485 区间选点
查看>>
poj 3518 Prime Gap
查看>>
poj 3539 Elevator——同余类bfs
查看>>
Qt笔记——官方文档全局定义(三)Macros宏
查看>>