【难】【数学】斐波那契数列的O(logn)解法

题目:《编程之美》 P163

class Matrix
{
public:
	unsigned int a11, a12, a21, a22;
	Matrix(int a, int b, int c, int d) :a11(a), a12(b), a21(c), a22(d){}
	//重载矩阵的乘法
	Matrix operator*(const Matrix &other)
	{
		Matrix r(0,0,0,0);
		r.a11 = a11*other.a11 + a12*other.a21;
		r.a12 = a11*other.a12 + a12*other.a22;
		r.a21 = a21*other.a11 + a22*other.a21;
		r.a22 = a21*other.a12 + a22*other.a22;
		return r;
	}
};

//计算矩阵A的m次方
Matrix MatrixPow(const Matrix &A,unsigned int m)
{
	Matrix res(1, 0, 0, 1);//单位矩阵
	Matrix cur = A;
	while (m)
	{
		if (m & 1)
			res = res*cur;
		cur = cur*cur;
		m = m >> 1;
	}
	return res;
}

unsigned int Fibonacci(int n)
{
	if (n < 0)
		throw new exception;
	if (n == 0 || n == 1)
		return n;
	Matrix A(1, 1, 1, 0);
	Matrix r = MatrixPow(A, n - 1);
	return r.a11;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值