分析
考虑1×2的矩阵【f[n-2],f[n-1]】。根据fibonacci数列的递推关系,我们希望通过乘以一个2×2的矩阵,得到矩阵【f[n-1],f[n]】=【f[n-1],f[n-1]+f[n-2]】很容易构造出这个2×2矩阵A,即:
所以,有 【 f [ 1 ] , f [ 2 ] 】 × A = 【 f [ 2 ] , f [ 3 ] 】 【f[1],f[2]】×A=【f[2],f[3]】 【f[1],f[2]】×A=【f[2],f[3]】又因为矩阵乘法满足结合律,故有: 【 f [ 1 ] , f [ 2 ] 】 × A n − 1 = 【 f [ n ] , f [ n + 1 ] 】 【f[1],f[2]】×A n-1=【f[n],f[n+1]】 【f[1],f[2]】×An−1=【f[n],f[n+1]】
这个矩阵的第一个元素即为所求。
上代码
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int mod=10000;
ll n;
struct matrix
{
ll m,n;//长,宽
ll f[20][20];//矩阵
}st,A,B;
matrix operator *(matrix a,matrix b)
{
matrix C;
C.n=a.n;C.m=b.m;
for(int i=1;i<=C.n;i++)
{
for(int j=1;j<=C.m;j++)
{
C.f[i][j]=0;
}
}
for(int k=1;k<=a.m;k++)
{
for(int i=1;i<=a.n;i++)
{
for(int j=1;j<=b.m;j++)
{
C.f[i][j]=(C.f[i][j]+a.f[i][k]*b.f[k][j]%mod)%mod;
}
}
}
return C;
}
void ksm(ll x)//递归写法
{
if(x==1)
{
A=st;
return;
}
ksm(x/2);
A=A*A;
if(x&1) A=A*st;
}
int main()
{
cin>>n;
st.n=2;st.m=2;
st.f[1][1]=0;st.f[1][2]=1;
st.f[2][1]=1;st.f[2][2]=1;
if(n<=2)
{
cout<<1;
return 0;
}
else
{
B.m=2;B.n=1;
B.f[1][1]=1;B.f[1][2]=1;
ksm(n-1);
B=B*A;
cout<<B.f[1][1];
}
return 0;
}