在时间复杂度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;
}

 

 

 

posted on 2012-04-07 10:22  NLP新手  阅读(2547)  评论(0编辑  收藏  举报

导航