由于斐波那契数列的性质,我们知道f[i]=f[i-1]+f[i-2]
这里按照矩阵的形式写[f[i],f[i+1]]=[f[i+1],f[i+2]]
所以,想要快速推出f[n],那就可以把,平方n-1次,输出右下角的数字
这里计算用到了快速幂
#include<bits/stdc++.h>
using namespace std;
long long n;
const int mod=1e9+7;
struct juzhen
{
unsigned long long a[3][3];
}temp,ans,fore;
juzhen mul(juzhen x ,juzhen y)
{
juzhen cnt;
for(int i=1;i<=2;i++)
for(int j=1;j<=2;j++)
{
unsigned long long ans=0;
for(int k=1;k<=2;k++)
{
ans+=(x.a[i][k]*y.a[k][j])%mod;
ans%=mod;
}
cnt.a[i][j]=ans;
}
return cnt;
}
juzhen pow(long long x)
{
if(x==0)
{
temp.a[1][1]=1;
temp.a[1][2]=0;
temp.a[2][1]=0;
temp.a[2][2]=1;
return temp;
}
if(x==1)
{
return fore;
}
if(x%2==1)
{
juzhen xa=pow((x-1)/2);
return mul(mul(xa,xa),fore);
}
else
{
juzhen xa=pow(x/2);
return mul(xa,xa);
}
}
int main()
{
scanf("%lld",&n);
fore.a[1][1]=0; fore.a[1][2]=fore.a[2][1]=fore.a[2][2]=1;
ans=pow(n-1);
printf("%lld\n",ans.a[2][2]);
return 0;
}