The Program of Algorithms ------- Diveide and Conquer ---- Fibonacci

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];
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值