洛谷 P1306 斐波那契公约数 (神奇结论+矩阵快速幂)

gcd(F[n],F[m])=F[gcd(n,m)]

有这个迷之结论

如果是比赛的话可能就打表找规律了

然后就是用矩阵快速幂了

矩阵为

1 1

1 0

很好推。

然后注意矩阵快速幂的题范围小于等于矩阵长度的时候要特判一下

同时保留后8位是模1e8, 不是1e9

#include<cstdio>
#include<cstring>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
#define _for(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;

typedef long long ll;
const int MOD = 1e8;
struct mat
{
	ll m[5][5];
	mat() { memset(m, 0, sizeof(m)); }
};

mat operator * (const mat& a, const mat& b)
{
	mat res;
	_for(i, 1, 2)
		_for(j, 1, 2)
			_for(k, 1, 2)
				res.m[i][j] = (res.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
	return res;
}

mat pow(mat a, ll b)
{
	mat res;
	_for(i, 1, 2) res.m[i][i] = 1;
	for(; b; b >>= 1)
	{
		if(b & 1) res = res * a;
		a = a * a;
	}
	return res;
}

ll gcd(ll a, ll b) { return !b ? a : gcd(b, a % b); }

int main()
{
	ll n, m;
	scanf("%lld%lld", &n, &m);
	ll c = gcd(n, m);
	if(c <= 2) { puts("1"); return 0; }
	mat A;
	A.m[1][1] = A.m[1][2] = A.m[2][1] = 1;
	A = pow(A, c - 2);
	printf("%lld\n", (A.m[1][1] + A.m[1][2]) % MOD);
	return 0;
}

上面这个方法是原始的矩阵在最后单独计算。乘法都是方阵

还有种比较复杂 写法,乘法是矩阵,但是比较通用。

#include<cstdio>
#include<cstring>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
#define _for(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;

typedef long long ll;
const int MOD = 1e8;
struct mat
{
	ll m[5][5];
	int r, c;
	mat() { memset(m, 0, sizeof(m)); }
};

mat operator * (const mat& a, const mat& b)
{
	mat res;
	_for(i, 1, a.r)
		_for(j, 1, b.c)
			_for(k, 1, a.c)
				res.m[i][j] = (res.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
	res.r = a.r, res.c = b.c; //不要漏 
	return res;
}

mat pow(mat a, ll b)
{
	mat res;
	res.m[1][1] = res.m[1][2] = 1;
	res.r = 1; res.c = 2;
	for(; b; b >>= 1)
	{
		if(b & 1) res = res * a;
		a = a * a;
	}
	return res;
}

ll gcd(ll a, ll b) { return !b ? a : gcd(b, a % b); }

int main()
{
	ll n, m;
	scanf("%lld%lld", &n, &m);
	ll c = gcd(n, m);
	if(c <= 2) { puts("1"); return 0; }
	mat A;
	A.m[1][1] = A.m[1][2] = A.m[2][1] = 1;
	A.r = A.c = 2;
	A = pow(A, c - 2);
	printf("%lld\n", A.m[1][1]);
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值