【算法】快速幂

算法-快速幂


前置知识
  • 倍增

思路

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

练习
相关推荐
D_evil__6 小时前
【Effective Modern C++】第五章 右值引用、移动语义和完美转发:24. 区分万能引用和右值引用
c++
铉铉这波能秀6 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马6 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
唐梓航-求职中6 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹6 小时前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll13045252986 小时前
Leetcode二叉树part4
算法·leetcode·职场和发展
林开落L6 小时前
从零开始学习Protobuf(C++实战版)
开发语言·c++·学习·protobuffer·结构化数据序列化机制
林开落L6 小时前
从入门到了解:Protobuf、JSON、XML 核心解析(C++ 示例)
xml·c++·json·protobuffer·结构化数据序列化机制
Queenie_Charlie6 小时前
stars(树状数组)
数据结构·c++·树状数组
颜酱6 小时前
二叉树遍历思维实战
javascript·后端·算法