another way of calculating N'th Fibonacci number is to take a base matrix F[2][2]={{1,1},{1,0}} and multiply it recursively. In this scenario suppose we wan to calculate Fibonacci of number 9,then power(F,n-1) will be called 4 times (power(F,8)->power(F,4)->power(F,4)->power(F,2) once n==1 or n==0 "return" statement will be executed and matrix F[2][2] will start to multiply 4 times recursively, after that all you need to do is to print the number at F[0][0] position,which in this particular scenario is 34. complexity is O(log n).
#include <stdio.h>
void multiply(int F[2][2], int M[2][2]);
void power(int F[2][2], int n);
/* function that returns nth Fibonacci number */
int fib(int n)
{
int F[2][2] = {{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
/* Optimized version of power() in method 4 */
void power(int F[2][2], int n)
{
if( n == 0 || n == 1)
return;
int M[2][2] = {{1,1},{1,0}};
power(F, n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
}
void multiply(int F[2][2], int M[2][2])
{
int x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
/* Driver program to test above function */
int main()
{
int n;
scanf("%d",&n);
printf("%d", fib(n));
getchar();
return 0;
}