快速幂与矩阵快速幂
(一)快速幂模板(整数快速幂计算x^N )
举个栗子
十进制数 11 = 二进制数1011
3^11 = 3^1011 = 3^8 3^2 3^1
int QuickPow(int x,int N)
{
int res = x; //res表示当前底数
int ans = 1; //ans表示当前值
whlle(N)
{
if(N&1)
{
ans = ans * res;
}
res = res * res;
N = N >> 1;
}
return ans;
}
注意理解板子中 res 和 ans 的作用
(二)矩阵快速幂 (矩阵A的M次幂,A^M )
先献上板子
struct Matrix
{
int m[maxn][maxn];
}ans,res;
//计算矩形乘法的函数,参数是矩阵 A 和矩阵 B 和一个 n(阶数)
Maxtrix Mul(Maxtrix A, Maxtrix B, int n)
{
Maxtrix temp;//定义一个临时矩阵,存放A*B的结果
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
temp.m[i][j] = 0;//初始化temp
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][j]*B.m[i][j];
return temp;
}
void QuickPower(int N, int n)
{
//对应整数快速幂,矩阵快速幂的 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)
{
if(N&1)
ans = Mul(res, res);
res = Mul(res, res);
N = N >> 1;
}
}
例题
(1)众所周知:斐波那契数列递推公式为:F[n] = F[n-1] + F[n-2]. 其中f[1]=1,f[2]=1,求F[n]的值;
(2)变式 F[n] = AF[n-1] + BF[n-2]. 其中f[1]=1,f[2]=1,求F[n]的值;
(3)变式 F[n] = AF[n-1] + BF[n-2] + C. 其中f[1]=1,f[2]=1,求F[n]的值;