【算法】快速幂

算法-快速幂


前置知识
  • 倍增

思路

我们要求 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;
}

练习
相关推荐
erzong2315 小时前
Linux操作系统:线程概念与控制
linux·算法
wuminyu6 小时前
JMM学习总结:深入理解happens-before关系
java·linux·c语言·jvm·c++
Nil2086 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展
xxwl5856 小时前
区域赛分类题解
c++·笔记·学习·算法
m0_674571976 小时前
力扣 hot 100 python
python·算法·leetcode
青少儿编程课堂7 小时前
蓝桥杯+全国青少年信息素养大赛+电子学会PythonC/C++考级:最长公共子序列LCS解析
c++·python·算法·bfs·信息学竞赛
倚楼听风语8 小时前
Kotlin 协程与 suspend 原理详解
java·算法·kotlin
程序员清风8 小时前
双指针与滑动窗口:高效处理连续区间
开发语言·算法
代钦塔拉8 小时前
【C++/Qt 进阶】设计模式系列(2):工厂模式——从游戏角色到披萨店
c++·算法·设计模式
思茂信息8 小时前
电磁仿真学涉及哪些算法?
人工智能·算法·数学建模·matlab·emc·电磁仿真·仿真辐射