【算法】快速幂

算法-快速幂


前置知识
  • 倍增

思路

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

练习
相关推荐
geovindu16 小时前
python:DecisionTree
开发语言·后端·python·算法
ShineWinsu16 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu17 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
闻缺陷则喜何志丹18 小时前
【数论】P10136 [USACO24JAN] Cowlendar S|普及+
c++·数学·数论·洛谷
apcipot_rain19 小时前
某游戏公司C++游开实习 机试复盘
c++·游戏
AllData公司负责人20 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康21 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
炸膛坦客21 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++
夜不会漫长21 小时前
C++:C++11特性
开发语言·c++·算法