【算法】快速幂

算法-快速幂


前置知识
  • 倍增

思路

我们要求 a n a^n an。

简单的方法是 a n = a n − 1 ⋅ a a^n=a^{n-1}\cdot a an=an−1⋅a

但是我们不妨使用倍增的思想

若 2 ∣ n 2\mid n 2∣n,则 a n = a n 2 2 a^n={a^{\frac n 2}}^2 an=a2n2

若 2 ∤ n 2\nmid n 2∤n,则 a n = a ⌊ n 2 ⌋ 2 ⋅ a a^n={a^{\lfloor{\frac n 2}\rfloor}}^2\cdot a an=a⌊2n⌋2⋅a


算法参数
  • 时间复杂度: O ( log ⁡ n ) O(\log n) O(logn)
  • 空间复杂度: O ( 1 ) O(1) O(1)

实现代码
  • 基础版本
cpp 复制代码
int pow(int x,int y){
    int res=1;
    while (y){
        if (y&1) res=res*x;
        x=x*x;
        y>>=1;
    }
    return res;
}
  • 取模版本
cpp 复制代码
int pow(int x,int y,int M){
    int res=1;
    while (y){
        if (y&1) res=res*x%M;
        x=x*x%M;
        y>>=1;
    }
    return res;
}

练习
相关推荐
千里码aicood3 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
码匠许师傅3 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
做cv的小昊4 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له4 小时前
World-In-World: World Models in a Closed-Loop World
算法
无名猿4 小时前
new/delete 与 malloc/free:为什么绝对不能混用
c++·内存管理·现代c++·踩坑记录
2601_962218616 小时前
C++中decltype关键字的实现
开发语言·c++
Discipline10296 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
繁华的地方不一定留下你的脚印6 小时前
C++ std::variant 与 std::visit:安全保存多种类型,写清每个处理分支
开发语言·c++
XuCoder6 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法