在对于一些有规律的序列中,我们可以通过求出一个初始矩阵,通过快速幂进行计算
例如:
斐波那契数列
1 , 1, 2, 3, .........
在斐波那契数列中,从第三项开始,每一项都等于前两项的和
因此,我们可以得到公式 F(n) = F(n - 1) + F(n - 2);
转换为矩阵乘法就可以有
利用递归不断重复这个过程
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct node
{
int num[2][2];
} A, End;
node X(node a, node b)
{
node c;
memset(c.num, 0, sizeof(c.num));
for(int k = 0; k < 2; k++)
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; j++)
c.num[k][i] += a.num[k][j] * b.num[j][i];
return c;
}
node P(node a, int n)
{
if(n == 1)
return a;
node K = P(a, n / 2);
if(n % 2 == 0)
return X(K, K);
else
return X(a, X(K, K));
}
int main()
{
int n;
A.num[0][0] = 1;
A.num[0][1] = 1;
A.num[1][0] = 1;
A.num[1][1] = 0;
while(~scanf("%d", &n))
{
if(n == 1)
cout << "1" << endl;
else
{
End = P(A, n - 1);
printf("%d\n", End.num[0][0]);
}
}
return 0;
}
还是有小Bug,需要再改改