Files
SiMengWebSite_Notes/docs/blog/technology/fast-power-algorithm.md
祀梦 13404a7430 feat(docs): 添加多篇技术博客和竞赛文章
添加快速幂算法详解、蓝桥杯竞赛题解、Python字符串格式化指南等技术文章
新增多张封面图片并调整博客封面布局配置
2026-01-09 16:10:29 +08:00

79 lines
2.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 快速幂算法详解
createTime: 2026/01/09 16:05:00
cover: /images/elysia/9.jpg
coverStyle:
layout: left
permalink: /archives/1325a3bf-91d7-43ff-9630-e894549e12c1/
---
## 简介
快速幂算法是用于快速计算的算法,可以用于快速的处理大整数幂的场景。
最简单的 for 循环求数字的 n 次幂需要 $O(n)$ 的时间复杂度。快速幂方法可以达到 $O(\log N)$ 的时间复杂度。
快速幂的核心思想是将指数拆分,以达到快速计算的目的。
## 快速幂 - 二进制法
### 原理
二进制法的核心思想是将指数转换为二进制形式,通过逐位处理并结合平方运算减少乘法次数。
**二进制分解指数**
将指数 $n$ 表示为二进制形式,例如 $n=13$ 对应二进制为 `1101`,即 $13=8+4+1=2^3+2^2+2^0$。
**幂的拆分**
根据二进制分解,$a^n=a^{2^k} \times a^{2^{k-1}} \times \dots \times a^{2^0}$,其中仅当二进制位为 1 时,对应项被保留。
**逐位处理与平方加速**
- 从最低位到最高位依次处理二进制每一位。
- 若当前位为 1则将当前的底数累乘到结果中。
- 每一步将底数平方,为处理更高位做准备。
### 代码示例
```python
def power(base, exp):
res = 1
while exp > 0:
if exp & 1:
res *= base
base *= base
exp >>= 1
return res
```
## 快速幂 - 折半法
### 原理
折半法的核心公式如下:
我们要快速计算 $a$ 的 $n$ 次方:
- 当 $n$ 为奇数的时候:$a^n = a \cdot (a^2)^{(n-1)/2}$
- 当 $n$ 为偶数的时候:$a^n = (a^2)^{n/2}$
- 当 $n$ 为 0 的时候,直接返回 1
通过递归或迭代,将大指数问题分解为小指数问题,最后合并结果。
### 代码示例
```python
def power(base, exp):
if exp == 0: return 1
half = power(base, exp // 2)
return half * half * (base if exp % 2 else 1)
```
## 两种方法对比
| 特性 | 二进制法 | 折半法 |
| :--- | :--- | :--- |
| **实现方式** | 迭代 + 位运算 | 递归/迭代 + 分治 |
| **时间复杂度** | $O(\log N)$ | $O(\log N)$ |
| **空间复杂度** | $O(1)$ | $O(\log N)$ (递归) |
两者都可以实现在指数时间解决问题,二进制方法比折半法更加的省空间。