斐波那契数列之矩阵快速幂

对于任意给出的n,给出斐波那契数列的第n项的后四位数

代码如下

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const long long MOD = 1e4;
typedef long long ll;
struct mat
{
	long long a[2][2];
	mat(){ a[0][0] = a[0][1] = a[1][0] = 1; a[1][1] = 0;}
	mat(ll k){ a[0][0] = a[0][1] = a[1][0] = a[1][1] = k; }
	mat(ll c, ll d) { a[0][0] = a[1][1] = d; a[1][0] = a[0][1] = c; }
};
/*mat init(mat x)
{
	x.a[0][0] = x.a[0][1] = x.a[1][0] = 1;
	x.a[1][1] = 0;
	return x;
}*/
mat operator*(mat x, mat y)
{
	mat ans(0);
	for (int i = 0; i <= 1; i++)
	{
		for (int j = 0; j <= 1; j++)
		{
			for (int k = 0; k <= 1; k++)
			{
				ans.a[i][j] = (ans.a[i][j] +  x.a[i][k] * y.a[k][j])%MOD;
			}
		}
	}
	return ans;
}
mat qpow(ll p)
{
	mat x;
	mat ans(0,1); //ans = init(ans);
	while (p)
	{
		if (p & 1) ans = ans * x;
		x = x * x;
		p >>= 1;
	}
	return ans;
}
void put(mat x)
{
	for (int i = 0; i <= 1; i++)
	{
		for (int j = 0; j <= 1; j++)
		{
			cout << x.a[i][j] << " " ;
		}
		cout << endl;
	}
}
int main()
{
	ll t;
	while (cin >> t)
	{
		if (t < 0) break;
		//if (!t) cout << 0 << endl;
		mat m = qpow(t);
		cout << m.a[0][1] << endl;
		//put(m);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值