矩阵快速幂
关于矩阵乘法,请自行了解。
学习大佬博客矩阵快速幂基础
以下代码是基于大佬博客进行修改与完善的
#include<iostream>
using namespace std;
const int Maxn = 100;
struct Matrix//结构体 矩阵类型
{
int m[Maxn][Maxn];
}ans, res;
/*计算矩阵乘法的函数*/
Matrix Mul(Matrix A, Matrix B, int n)
{
Matrix temp;//定义一个临时的矩阵,存放A*B的结果
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
temp.m[i][j] = 0;//初始化为0
}
}
for (int i = 1; i <= n; i++)//两个矩阵相乘
{
for (int j = 1; j <= n; j++)
{
for (int k = 1; k <= n; k++)
{
temp.m[i][j] += A.m[i][k] * B.m[k][j];
}
}
}
return temp;
}
/*快速幂求矩阵res的N次幂*/
void Quick_power(int N,int n)
{
/*将矩阵ans初始化为单位矩阵*/
/*即对角线赋值为1,其余为0*/
/*任何矩阵乘以ans为本身*/
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)ans.m[i][j] = 1;
else ans.m[i][j] = 0;
}
}
while (N)//N幂指数
{
if (N & 1)
ans = Mul(ans, res,n);
res = Mul(res, res, n);
N >>= 1;//去掉末位
}
}
int main()
{
int N,n;//N幂指数,n阶数
cin >>N>> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> res.m[i][j];
}
}
Quick_power(N, n);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cout << ans.m[i][j] << " ";
}
cout << endl;
}
return 0;
}
欢迎批评指正!