快速幂、矩阵快速幂板子

快速幂:

#include <iostream>
using namespace std;

int quickPow(int A,int n){
	int res = 1;
	int mul = A;
	while(n){
		if(n&1){
			res *= mul;			
		}
		mul *= mul;
		n /= 2;
	}
	return res;
}

int main(){
	cout<<quickPow(3,4);
	return 0;
} 

矩阵快速幂:

#include<iostream>
#include<cstring> 

using namespace std;

const int maxn = 2;

struct Matrix{
	int a[maxn][maxn];
	void init(){ //初始化为单位矩阵
		memset(a, 0, sizeof(a));
		for(int i = 0;i < maxn;i++){
			a[i][i] = 1;
		}
	}
};

Matrix mulMatrix(Matrix a,Matrix b){//矩阵乘法
	Matrix ans;
	for(int i = 0;i < maxn;i++){
		for(int j = 0;j < maxn;j++){
			ans.a[i][j] = 0;
			for(int k = 0;k < maxn;k++){
				ans.a[i][j] += a.a[i][k] * b.a[k][j];
				ans.a[i][j] %= 10000;
			}
		}
	}
	return ans;
}

Matrix quickPow(Matrix m,int n){//矩阵快速幂 
	Matrix res;
	res.init();
	while(n){
		if(n&1){
			res = mulMatrix(res,m);
		}
		m = mulMatrix(m,m);
		n = n/2;
	}
	return res;
}

int main(){
	Matrix m;
	//随便一个二维矩阵
	m.a[0][0] = 0;
	m.a[0][1] = 1;
	m.a[1][0] = 1;
	m.a[1][1] = 0;
	Matrix b =	quickPow(m,10);
	for(int i = 0;i < maxn;i++){
		for(int j = 0;j < maxn;j++){
			cout<<b.a[i][j]<<" "; 
		}
		cout<<endl;
	}
	return 0;
}

矩阵快速幂的应用:求斐波那契数列n个数
思想:将求斐波那契数列过程转为矩阵相乘
在这里插入图片描述
其中
在这里插入图片描述
即:[f(1000), f(999)] = [f(2),f(1)] * A^998 其中[f(2),f(1)] = [1,1];
因此我们要求f(n)只需求出T = A^(n-2),然后再取T[0][0] + T[1][0]即为我们要求的

代码如下:

#include<iostream>
#include<cstring> 

using namespace std;

const int maxn = 2;

struct Matrix{
	int a[maxn][maxn];
	void init(){ //初始化为单位矩阵
		memset(a, 0, sizeof(a));
		for(int i = 0;i < maxn;i++){
			a[i][i] = 1;
		}
	}
};

Matrix mulMatrix(Matrix a,Matrix b){//矩阵乘法
	Matrix ans;
	for(int i = 0;i < maxn;i++){
		for(int j = 0;j < maxn;j++){
			ans.a[i][j] = 0;
			for(int k = 0;k < maxn;k++){
				ans.a[i][j] += a.a[i][k] * b.a[k][j];
				ans.a[i][j] %= 10000;
			}
		}
	}
	return ans;
}

Matrix quickPow(Matrix m,int n){//矩阵快速幂 
	Matrix res;
	res.init();
	while(n){
		if(n&1){
			res = mulMatrix(res,m);
		}
		m = mulMatrix(m,m);
		n = n/2;
	}
	return res;
}

int main(){
	Matrix m; //为矩阵A
	m.a[0][0] = 1;
	m.a[0][1] = 1;
	m.a[1][0] = 1;
	m.a[1][1] = 0;
	int n;
	cin>>n;
	Matrix b =	quickPow(m,n - 2);
	cout<<b.a[0][0] + b.a[1][0];
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值