2019牛客暑期多校训练营(第九场)A:The power of Fibonacci(中国剩余定理)

【题解】

1e9的循环节太大了显然复杂度不行,我们考虑把1e9拆开求循环节,然后利用中国剩余定理求解。

1e9 拆成 2^9*5^9 时,512 与 1953125 互质且循环节分别为 768 和 7812500 ,复杂度可以接受,可行。所以我们只需要算出最终答案在对 512 和 1953125 取模下的答案,再用中国剩余定理将两个答案合并就能得到答案了。

斐波那契数列对任意值取模都有循环节吗?

感谢@jk_chen_acmer:不单是斐波那契,循环节都可以拆成两个互质的循环节,再通过中国剩余定理合并(取模前提下),因为%pq的循环节可以通过%p和%q的循环节推导。

【代码】

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int P=1e9;
const int P1=512; //2^9
const int P2=1953125; //5^9
const int N=768; //2^9的循环节
const int M=7812500; //5^9的循环节
int n,m,F[M+10];
int fast(int a,int b){
	int res=1;
	while(b){
		if(b&1)res=1ll*res*a%P;
		a=1ll*a*a%P;
		b>>=1;
	}
	return res;
}
int calc(int d,int P){
	return (1ll*n/d*F[d-1]%P+F[n%d])%P;
}
int ex_gcd(int a,int b){
	while(b%P1!=a) b+=P2;
	return b;
}
int main()
{
    scanf("%d%d",&n,&m);
	F[0]=0,F[1]=1;
	for(int i=2;i<M;i++)
        F[i]=(F[i-1]+F[i-2])%P;
	for(int i=1;i<M;i++)
        F[i]=(F[i-1]+fast(F[i],m))%P;
	printf("%d\n",ex_gcd(calc(N,P1),calc(M,P2)));
	return (0-0);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值