矩阵一维递推 菲波拉契数

算法:

利用矩阵乘法求解递推,时间复杂度O(lgn)

View Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<string>
#include<math.h>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
#define MAXN 10
#define MOD 2009
int N;

class Matrix
{
  public:
     int mt[MAXN][MAXN];
     Matrix  Multiply(Matrix);
     Matrix  Add(Matrix);
     Matrix  quickpower(int);
     void  Build(int ); //构造一个m * m维矩阵 
     void SetSize(int);
     void SetMod(int);
  private:
     int size;
   //  int MOD;      
};

void Matrix::Build(int n)
{ 
   size = n;
   mt[1][1] = 0;
   mt[1][2] = 1;
   mt[2][1] = 1;
   mt[2][2] = 1;  
}

void Matrix::SetMod( int x )
{
   //MOD = x;       
}

void Matrix::SetSize( int s )
{
   for( int i = 1; i <= s; i++)
      for( int j = 1; j <= s; j++)
          mt[i][j] = 0;
   size = s;     
     
}

Matrix Matrix::Add(Matrix A)
{
   Matrix C;
   for( int i = 1; i <= size; i++)
     for( int j = 1; j <= size; j++)
         C.mt[i][j] = mt[i][j] + A.mt[i][j];                     
   return C;
}

Matrix Matrix::Multiply(Matrix A)
{
   Matrix C;
   C.size = size;
   for( int i = 1; i <= size; i++)
   {
       for( int j = 1; j <= size; j++)
       {
            
            int sum = 0;
            for( int k = 1; k <= size; k++)
            {
                 
               sum += (A.mt[i][k] % MOD) * (mt[k][j] % MOD);
               sum %= MOD;
                 
            }     
            C.mt[i][j] = sum;
            
       }     
        
        
   }
   return C;     
}

Matrix Matrix::quickpower(int n)
{
  Matrix Temp1;
  Temp1.Build(2);
  size = 2;
  for( int i = 1; i <= 2; i++)
    for( int j = 1; j <= 2; j++)
         mt[i][j] = 1;
  while( n > 0 )
  {
    if( n&1 )
        (*this) = (*this).Multiply(Temp1);
    n >>= 1;
    Temp1 = Temp1.Multiply(Temp1);
  }
  return *this;       
}

int main( )
{
  while( scanf("%d",&N), N )
  {
    Matrix A;
    A.quickpower(N - 1);
    printf("%d %d\n",A.mt[1][2],A.mt[2][2]);
         
  }  
  return 0;
}

posted on 2012-08-16 21:28  more think, more gains  阅读(207)  评论(0编辑  收藏  举报

导航