题目:POJ 3070 Fibonacci(矩阵快速幂简单应用)

版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/87261226

公式如下
在这里插入图片描述
即求矩阵n次幂后的第1行第2列的数

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MOD 10000
using namespace std;

typedef long long ll;
struct mat{
	int a[5][5];
};
mat mul(mat x, mat y)
{
	mat t;
	memset(t.a, 0, sizeof(t.a));
	for (int i=1; i<=2; i++){
		for (int j=1; j<=2; j++){
			for (int k=1; k<=2; k++){
				t.a[i][j]+=x.a[i][k] * y.a[k][j];
				t.a[i][j]%=MOD;
			}
		}
	}
	return t;
}
void quick_mod(int n)
{
	mat ans, res;
	res.a[1][1]=1;
	res.a[1][2]=1;
	res.a[2][1]=1;
	res.a[2][2]=0;
	
	for (int i=1; i<=2; i++)
		for (int j=1; j<=2; j++)
			if (i==j)	ans.a[i][j]=1;
			else	ans.a[i][j]=0;
	
	while (n){
		if (n&1)
			ans=mul(ans, res);
		res=mul(res, res);
		n>>=1;
	}
	printf("%lld\n", ans.a[1][2]);
}
int main()
{
	ll n;
	while (scanf("%lld", &n)!=EOF && n!=-1){
		quick_mod(n);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42172261/article/details/87261226