矩阵快速幂实现斐波那契数列

正常求斐波那契数列的暴力算法时间复杂度为O(n),当数据量过大时时间过慢,通过矩阵快速幂的方法可以将时间复杂度降低至O(logN).

矩阵乘法的实现这里就不说了,直接说最关键的步骤

这里偷了张网上的图=-=。

也就是说我们可以把斐波那契数列求解化作一个类似等比数列的感觉,不过里面每一项都是矩阵,然后通过快速幂计算每一项

这里放上实现的代码,数据过大时对1e9+7取模:

#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9+7;
#define int long long
struct Matrix
{
	int a[3][3];
	Matrix(){
		memset(a,0,sizeof(a));
	}
	Matrix operator* (const Matrix &b) const{    //重载矩阵乘法
		Matrix res;
		for(int i=1;i<=2;i++){
			for(int j=1;j<=2;j++){
				for(int k=1;k<=2;k++){
					res.a[i][j] = (res.a[i][j] +a[i][k]*b.a[k][j])%mod;
				}
			}
		}
		return res;
	}
};
signed main()
{
	int n; cin>>n;
	Matrix base,ans;  //base为每次乘的矩阵,ans为斐波那契数列的第1 2项
	base.a[1][1] =0;
	base.a[1][2] = base.a[2][1] =base.a[2][2] =1;
	ans.a[1][1] = ans.a[1][2] =1;
	if(n>2){
		n-=2;
		while(n) {        //快速幂实现
		if(n &1) ans = (ans*base);
		base =( base*base);
		n/=2;
	}
	}
	cout<<ans.a[1][2]%mod;
	
	return 0;
}

可以当作矩阵快速幂的模板,不过结构体里面矩阵开的大小要符合具体题目要求。

来一道变式题:

一样的递推公式,我们只需要把矩阵换一下即可(注意从0项开始的)

手写将就看

AC代码:

#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9+7;
#define int long long
void fast ()
{cin.tie(0);    cout.tie(0);    ios::sync_with_stdio(false);}
struct Matrix
{
	int a[5][5];
	Matrix(){
		memset(a,0,sizeof(a));
	}
	Matrix operator* (const Matrix &b) const{    //重载矩阵乘法
		Matrix res;
		for(int i=1;i<=4;i++){
			for(int j=1;j<=4;j++){
				for(int k=1;k<=4;k++){
					res.a[i][j] = (res.a[i][j] +a[i][k]*b.a[k][j])%mod;
				}
			}
		}
		return res;
	}
};
signed main()
{
	fast();
	int n; cin>>n;
	Matrix base,ans;  //base为每次乘的矩阵,ans为初始数列的样子
	ans.a[1][1] =3; ans.a[1][2] =1;ans.a[1][3] =2;ans.a[1][4] =3; 
	 //初始化前三项
	base.a[1][1] = base.a[3][2] =base.a[4][3] = base.a[2][4] = base.a[1][4] =1;
	base.a[3][4] = 2;  base.a[4][4] = 3;
	if(n<=2){
		if(n==1) cout<<2;
		else if(n==2) cout<<3;
	}
	else if(n>2){
		int temp = n-2;
		while(temp) {        //快速幂实现
		if(temp &1) ans = (ans*base);
		base =( base*base);
		temp/=2;
		}
	cout<<ans.a[1][4]%mod;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值