How does this formula work?The formula can be derived from above matrix equation.

Taking determinant on both sides, we get(-1)n = Fn+1Fn-1 – Fn2Moreover, since AnAm = An+m for any square matrix A, the following identities can be derived (they are obtained form two different coefficients of the matrix product)

To get the formula to be proved, we simply need to do followingIf n is even, we can put k = n/2If n is odd, we can put k = (n+1)/2

// Create an array for memoization

intf[MAX] = {0};

// Returns n'th fuibonacci number using table f[]

intfib(intn)

{

// Base cases

if(n == 0)

return0;

if(n == 1 || n == 2)

return(f[n] = 1);

// If fib(n) is already computed

if(f[n])

returnf[n];

intk = (n & 1)? (n+1)/2 : n/2;

// Applyting above formula [Note value n&1 is 1

// if n is odd, else 0.

f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1))

: (2*fib(k-1) + fib(k))*fib(k);

returnf[n];

}

DP:

staticintfib(intn)

{

/* Declare an array to store Fibonacci numbers. */

intf[] = newint[n+1];

inti;

/* 0th and 1st number of the series are 0 and 1*/

f[0] = 0;

f[1] = 1;

for(i = 2; i <= n; i++)

{

/* Add the previous 2 numbers in the series

and store it */

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

}

returnf[n];

}

intfib(intn)

{

inta = 0, b = 1, c, i;

if( n == 0)

returna;

for(i = 2; i <= n; i++)

{

c = a + b;

a = b;

b = c;

}

returnb;

}

Method 4 ( Using power of the matrix {{1,1},{1,0}} )This another O(n) which relies on the fact that if we n times multiply the matrix M = {{1,1},{1,0}} to itself (in other words calculate power(M, n )), then we get the (n+1)th Fibonacci number as the element at row and column (0, 0) in the resultant matrix.

The matrix representation gives the following closed expression for the Fibonacci numbers: