矩阵快速幂求斐波那契数列

xiaoxiao2021-02-28  110

#include <iostream> #include <vector> #include <algorithm> #include <cstdio> using namespace std; typedef long long LL; const int MAXN=1e4+5; const int MOD=1e9+7; typedef vector<int> vec; typedef vector<vec> mat; LL n; mat mul(mat &A,mat &B) { mat C(A.size(),vec(B[0].size())); for(int i=0;i<A.size();i++){ for(int k=0;k<B.size();k++){ for(int j=0;j<B[0].size();j++){ C[i][j]=(C[i][j]+A[i][k]*B[k][j])%MOD; } } } return C; } mat pow(mat A,LL n) { mat B(A.size(),vec(A.size())); for(int i=0;i<A.size();i++) B[i][i]=1; while(n>0) { if(n&1) B=mul(B,A); A=mul(A,A); n>>=1; } return B; } void solve() { mat A(2,vec(2)); A[0][0]=1;A[0][1]=1; A[1][0]=1;A[1][1]=0; A=pow(A,n); printf("%d\n",A[1][0]); } int main() { while(scanf("%lld",&n)!=EOF) { solve(); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-41247.html

最新回复(0)