zoukankan      html  css  js  c++  java
  • [板子]矩阵快速幂求解斐波那契

    在斐波那契数列之中

    f[i] = 1*f[i-1]+1*f[i-2]  f[i-1] = 1*f[i-1] + 0*f[i-2];

    所以

    就这两幅图完美诠释了斐波那契数列如何用矩阵来实现。

    摘自:http://blog.csdn.net/nyist_tc_lyq/article/details/52981353

    #include<bits/stdc++.h>
    #define LL long long 
    using namespace std;
    const long long pi=1000000007;
    struct node{
        long long a[3][3];
    }t1;
    
    long long n,k;
    node X(node x,node y){
          node box;
        
        for(LL i=1;i<=2;i++){
            for(LL j=1;j<=2;j++){
                box.a[i][j]=0;
            }
        }
        
        for(LL i=1;i<=2;i++){
            
            for(LL j=1;j<=2;j++){
                
                for(LL k=1;k<=2;k++){
                    
                    box.a[i][j]=(box.a[i][j]+(x.a[i][k]*y.a[k][j])%pi)%pi;
                    
                }
            }
        }
        
        return box;
    }
    void power(long long kk){
        node ans;
        kk-2;
        ans.a[1][1]=1;ans.a[1][2]=1;
        ans.a[2][1]=1;ans.a[2][2]=0;
    
        while(kk!=0){
            if(kk&1==1){
                ans=X(ans,t1);
            }
            kk>>=1;
            t1=X(t1,t1);
            
        }
        cout<<ans.a[2][2]<<endl;
    }
    int main(){
        cin>>n;
        if(n==0)
            cout<<"0"<<endl;
        else if(n==1||n==2)
            cout<<"1"<<endl;
        else{
            t1.a[1][1]=1;t1.a[1][2]=1;
            t1.a[2][1]=1;t1.a[2][2]=0;
    
            power(n);
        }
        return 0;
    }
  • 相关阅读:
    09_ssh服务器的安装和使用
    08_linux下的文件压缩和解压
    38-自定义异常类
    37-手动抛出异常对象
    DataGrip 2020.1 安装与激活
    36-异常的处理
    35-异常
    node+ajax实战案例(1)
    ajax前后端交互原理(7)
    ajax前后端交互原理(5)
  • 原文地址:https://www.cnblogs.com/Fylsea/p/7812146.html
Copyright © 2011-2022 走看看