Saturday 4 August 2012

Find nth Fibonacci number in less than 0(n).


#include<iostream.h>
#include<conio.h>

int f[2][2]={1,1,1,0};
int m[2][2]={1,1,1,0};

void multiply(int b[][2])
{
      int temp[2][2]={0};
      for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                  for(int k=0;k<2;k++)
                        temp[i][j]+=m[i][k]*b[k][j];
      for(i=0;i<2;i++)
            for(j=0;j<2;j++)
                  m[i][j]=temp[i][j];
}

void fibo(int n)
{
      if(n>1)
      {
            fibo(n/2);
            multiply(m);
            if(n%2==1)
                  multiply(f);
      }
      else
            return;
}




void main()
{
      clrscr();
      int n;
      cout<<"Element Number : ";
      cin>>n;
      fibo(n-2);
      if(n==1)
            cout<<0;
      else
            cout<<m[0][0];
      getch();
}

2 comments:

  1. Fibonacci recurrence is F(n+1) = F(n) + F(n-1) but we can represent this in the form a matrix as shown below:
    1 1 f(n) = f(n+1)
    1 0 * f(n-1) f(n)


    matrix A = [ [ 1 1 ] [ 1 0 ] ] .
    Multiplying A with [ F(n) F(n-1) ] gives us
    [ F(n+1) F(n) ]

    A* [ F(n) F(n-1) ] = [ F(n+1) F(n) ]


    A* [ F(1) F(0) ] = [ F(2) F(1) ]
    A* [ F(2) F(1) ] = [ F(3) F(2) ] = A^2 * [ F(1) F(0) ]
    A* [ F(3) F(2) ] = [ F(4) F(3) ] = A^3 * [ F(1) F(0) ]
    ..
    ..
    ..
    ..
    A* [ F(n) F(n-1) ] = [ F(n+1) F(n) ] = A^n * [ F(1) F(0) ]

    ReplyDelete
  2. Thanks! Here's another good solution as well:


    http://www.programmerinterview.com/index.php/recursion/find-nth-fibonacci-number/

    ReplyDelete