• 在时间复杂度O(logn)下求Fibonacci数列


    时间复杂度为O( n )的方法:

    long long Fibonacci( unsigned n )   
    {   
          int result[2] = {0, 1};   
          if(n < 2)   
                return result[n];   
    
          long long   fibOne = 0;   
          long long   fibTwo = 1;   
          long long   fibThree ;   
        
          for(unsigned int i = 2; i <= n; ++ i)   
           {   
                 fibThree = fibOne + fibTwo;   
          fibOne = fibTwo ;   
                 fibNTwo = fibThree;   
            }   
            return fibThree;   
    }
     
    
    /*
    下面介绍一种时间复杂度是O(logn)的方法:
    
    对于斐波那契数列1,1,2,3,5,8,13…….有如下定义:
    
    F( n ) = F( n-1 ) + F( n-2 )
    F( 1 ) = 1
    F( 2 ) = 1
    
    矩阵形式:
    
    [ F( n+1 ) ,  F( n ) ] = [ F( n ) , F( n-1 ) ] * Q  其中 [ F( n+1 ) ,  F( n ) ]为行向量,Q = { [ 1, 1 ]; [ 1, 0 ] }为矩阵
    
    则 [ F( n+1 ) , F( n ) ]=[ 1 , 0 ] * Qn , 
    */
     
    struct Matrix    
    {          
           long long m_00, m_01, m_10, m_11;   
       Matrix ( long long m00 = 0,  long long m01 = 0,  long long m10 = 0,   long long m11 = 0 )    
           :m_00( m00 ), m_01( m01 ), m_10( m10 ), m_11( m11 )     
           {    
           }    
    };
     
    
    Matrix MatrixMultiply (  const Matrix & m1, const Matrix & m2    )    
    {  
      long long m00 = m1.m_00 * m2.m_00 + m1.m_01 * m2.m_10;
      long long m01 = m1.m_00 * m2.m_01 + m1.m_01 * m2.m_11; 
      long long m10 = m1.m_10 * m2.m_00 + m1.m_11 * m2.m_10    
      long long m11 = m1.m_10 * m2.m_01 + m1.m_11 * m2.m_11; 
          return Matrix ( m00,  m01,  m10, m11 );    
    }
    
    Matrix MatrixPower( unsigned int n )    
    {    
           assert(n > 0);    
           Matrix m;    
           if( n == 1)    
           {    
                 m = Matrix(1, 1, 1, 0);    
           }    
          else if(n % 2 == 0)    
           {    
                 m = MatrixPower( n / 2 );    
                 m = MatrixMultiply( matrix, matrix );    
           }    
          else if( n % 2 == 1 )    
           {    
                 m = MatrixPower( (n - 1) / 2 );    
                 m = MatrixMultiply( m, m );    
                 m = MatrixMultiply( m, Matrix( 1, 1, 1, 0 ) );    
           }     
          return m;    
    }  
    long long Fibonacci( unsigned int n )
    {
          int result[2] = { 0, 1 };
          if( n < 2 )
                return result[ n ];
    
          Matrix Q = MatrixPower( n - 1 );  //注意:按定义式应该用[ 1, 0 ]*Q, 或者等价于{ [ 1 , 0 ]; [ 0, 0 ] }*Q, 但是因为显然结果相同,所以略去这一步。
          return Q.m_00;
    }

     

  • 相关阅读:
    记录一则ORACLE MOVE操作后重建索引过程被强制中断导致的ORA-8104案例
    Sybase数据库,普通表修改分区表步骤
    JavaWeb request对象常用操作
    JavaWeb 获取请求网络协议、IP、端口号、项目根路径
    java 从spring容器中获取注入的bean对象
    eclipse Java注释修改
    JavaWeb 获取ip地址
    jQuery源代码解析(1)—— jq基础、data缓存系统
    Http状态码
    Item 24: 区分右值引用和universal引用
  • 原文地址:https://www.cnblogs.com/kevinGaoblog/p/2435710.html
Copyright © 2020-2023  润新知