矩阵快速幂c++
时间: 2025-05-10 14:25:30 浏览: 36
### 矩阵快速幂算法的C++实现
矩阵快速幂是一种高效的计算方法,用于求解形如 \( A^n \) 的矩阵幂运算。通过利用分治法的思想,可以显著降低时间复杂度至 \( O(k^3 \log n) \),其中 \( k \) 是矩阵维度。
以下是完整的 C++ 实现代码:
#### 定义矩阵结构体
为了便于操作矩阵,我们先定义一个简单的矩阵类 `Matrix` 来封装基本功能。
```cpp
#include <iostream>
#include <vector>
using namespace std;
const int MOD = 1e9 + 7; // 可根据需求调整模数
// 定义矩阵类
struct Matrix {
vector<vector<long long>> mat;
int rows, cols;
// 构造函数初始化矩阵大小
Matrix(int r, int c): rows(r), cols(c), mat(vector<vector<long long>>(r, vector<long long>(c))) {}
// 返回单位矩阵 I (仅适用于方阵)
static Matrix identity(int size) {
Matrix res(size, size);
for (int i = 0; i < size; ++i) {
res.mat[i][i] = 1;
}
return res;
}
// 输出矩阵内容
void print() const {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << mat[i][j] << " ";
}
cout << endl;
}
}
};
```
#### 矩阵乘法实现
矩阵相乘的核心逻辑如下所示:
```cpp
// 矩阵乘法
Matrix multiply(const Matrix& a, const Matrix& b) {
Matrix result(a.rows, b.cols);
for (int i = 0; i < a.rows; ++i) {
for (int j = 0; j < b.cols; ++j) {
result.mat[i][j] = 0;
for (int k = 0; k < a.cols; ++k) {
result.mat[i][j] = (result.mat[i][j] + a.mat[i][k] * b.mat[k][j]) % MOD;
}
}
}
return result;
}
```
#### 快速幂实现
基于上述矩阵乘法,我们可以进一步实现矩阵快速幂算法:
```cpp
// 矩阵快速幂
Matrix matrixExponentiation(Matrix base, long long exp) {
Matrix result = Matrix::identity(base.rows); // 初始化为单位矩阵
while (exp > 0) {
if (exp % 2 == 1) { // 如果指数为奇数,则累乘当前基底到结果中
result = multiply(result, base);
}
base = multiply(base, base); // 基底平方
exp /= 2; // 指数减半
}
return result;
}
```
#### 测试代码
最后,在 `main` 函数中验证该算法的功能:
```cpp
int main() {
// 创建初始矩阵
Matrix m(2, 2);
m.mat = {{1, 1}, {1, 0}};
// 计算 Fibonacci 数列第 N 项对应的矩阵幂次
long long N = 10;
Matrix res = matrixExponentiation(m, N);
// 打印结果
res.print();
return 0;
}
```
---
### 关键点解析
1. **矩阵乘法规则**:两个矩阵能够相乘的前提条件是第一个矩阵的列数等于第二个矩阵的行数[^1]。
2. **快速幂原理**:类似于整数快速幂的操作方式,通过对指数不断取半并判断其奇偶性来减少不必要的重复计算[^2]。
3. **优化技巧**:为了避免溢出问题,通常会对中间结果进行取模操作,尤其是在处理大数值场景下[^4]。
---
阅读全文
相关推荐
















