$O(m^3log(n))$求斐波那契数列
\(O(m^3log(n))\)求斐波那契数列
利用这个递推式:\(\begin{pmatrix}F_{n+2}\\F_{n+1}\end{pmatrix}=\begin{pmatrix}1 & 1\\1 & 0\end{pmatrix}\begin{pmatrix}F_{n+1}\\F_{n}\end{pmatrix}\)
记\({\begin{pmatrix}1 & 1\\1 & 0\end{pmatrix}}\)为\(A\)
得到\({\begin{pmatrix}F_{n+1}\\F_{n}\end{pmatrix}}=A^n\begin{pmatrix}F_{1}\\F_{0}\end{pmatrix}=A^n{\begin{pmatrix}1\\0\end{pmatrix}}\)
// Created by CAD on 2020/2/18.
#include <bits/stdc++.h>
#define ll long long
using namespace std;
typedef vector<vector<ll> > mat;
const int mod=1e9+7;
mat operator *(mat &a,mat &b){
mat ans(a.size(),vector<ll>(b[0].size()));
for(int i=0;i<a.size();++i)
for(int j=0;j<b[0].size();++j)
for(int k=0;k<b.size();++k)
ans[i][j]=(ans[i][j]+a[i][k]*b[k][j])%mod;
return ans;
}
mat qpow(mat x,ll n){
mat ans(x.size(),vector<ll>(x.size()));
for(int i=0;i<x.size();++i)
ans[i][i]=1;
while(n){
if(n&1) ans=ans*x;
n>>=1,x=x*x;
}
return ans;
}
int main()
{
ll n;cin>>n;
mat a(2,vector<ll>(2));
a[0][0]=1,a[0][1]=1;
a[1][0]=1,a[1][1]=0;
mat ans=qpow(a,n);
cout<<ans[1][0]<<'\n';
return 0;
}
CAD加油!欢迎跟我一起讨论学习算法,QQ:1401650042