矩阵的快速幂及应用

以二阶矩阵为例。典型的斐波那契数列,就可以使用矩阵相乘来求解。

如果不考虑乘法的话,复杂度应该是lgn.

下面只给出计算矩阵快速幂的方法

#include <iostream>
#define L 10000
using namespace std;


class MyMatrix{
public:
	long long a00,a01,a10,a11;
	MyMatrix();
	MyMatrix(long long _a00, long long _a01, long long _a10, long long _a11):a00(_a00), a01(_a01), a10(_a10), a11(_a11) { }
	void print_matrix();
};


void MyMatrix::print_matrix(){
	cout << a00 << " " << a01 << endl << a10 << " " << a11 << endl;
}


const MyMatrix operator * (const MyMatrix & m1, const MyMatrix & m2){
	return MyMatrix(
		m1.a00 * m2.a00 + m1.a01 * m2.a10,
		m1.a00 * m2.a01 + m1.a01 * m2.a11,
		m1.a10 * m2.a00 + m1.a11 * m2.a10,
		m1.a10 * m2.a01 + m1.a11 * m2.a11
	);
}


//用 递归实现分治求解
const MyMatrix pow_matrix(const MyMatrix & m, long long n){
	if( n <= 1)
		return m;
	else{
		if( n & 1){ //奇数
			MyMatrix temp = pow_matrix(m, n/2);
			temp = temp * temp * m;
			return temp;
		}else{
			MyMatrix temp = pow_matrix(m, n/2);
			temp = temp * temp;
			return temp;
		}
	}
}


//不实用递归优化求解
MyMatrix ans2(1,0,0,1); //定义一个单位阵,存数最终结果
void pow_matrix_fast(const MyMatrix & m,long long n){
	MyMatrix temp = m;
//	temp.print_matrix();
	while(n){
		if(n & 1){ //奇数
			ans2 = ans2 * temp;
		}
		temp = temp * temp;
		n >>= 1;
		//temp.print_matrix();
	}
}


MyMatrix ans3(1,2,3,4);
void pow_matrix_fast2(const MyMatrix & m,long long n){
	MyMatrix temp = m;
//	temp.print_matrix();
	n--;
	while(n){
		if(n & 1){ //奇数
			ans3 = ans3 * temp;
		}
		temp = temp * temp;
		n >>= 1;
		//temp.print_matrix();
	}
}


int main() {
	MyMatrix m(1, 2, 3 ,4);
	MyMatrix ans = pow_matrix(m,6);
	ans.print_matrix();


	pow_matrix_fast(m, 6);
	ans2.print_matrix();


	pow_matrix_fast2(m, 6);
	ans3.print_matrix();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值