Definition:
Fn = 0 if n==0
Fn = 1 if n==1
Fn = F_n-1 + F_n-2 if n>1
Naive recursive Algorithm:
Time: Exponential.
Theorem:
(F_n+1, F_n ) [(1 1)]^n
(F_n, F_n-1) = [(1 0)]
The equation above is Matrix equation.
Time Analyze:
A and B are the a 2*2 Matrix, T(A*B) is O(1), as reference in the Power Algorithm.
A^n can use Divide and Conquer to solve. And the Time cost is Θ(lgn)
Realization --- CPP:
typedef long double(*TwoAndTwo)[2];
TwoAndTwo MatMulMat(long double lhs[2][2],long double rhs[2][2]){
TwoAndTwo res=new long double[2][2];
res[0][0]=lhs[0][0]*rhs[0][0]+lhs[0][1]*rhs[1][0];
res[0][1]=lhs[0][0]*rhs[0][1]+lhs[0][1]*rhs[1][1];
res[1][0]=lhs[1][0]*rhs[0][0]+lhs[1][1]*rhs[1][0];
res[1][1]=lhs[1][0]*rhs[0][1]+lhs[1][1]*rhs[1][1];
return res;
}
TwoAndTwo PowerOfMatrix(long double Arr[2][2] ,int n){
if(n>1){
if(n%2==0){ //n is even
return MatMulMat(PowerOfMatrix(Arr,n/2),PowerOfMatrix(Arr,n/2)); //recursively
}else{ //n is odd
return MatMulMat(MatMulMat(PowerOfMatrix(Arr,(n-1)/2),PowerOfMatrix(Arr,(n-1)/2)),Arr); //recursively
}
}else{
return Arr;
}
}
long double Fibonacci(int n){
if(n==0){
return 0;
}
long double m_arr[2][2]={{1,1},{1,0}};
TwoAndTwo b=PowerOfMatrix(m_arr,n);
return b[0][1];
}