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

你可能感兴趣的文章
npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
查看>>
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>