The power of Fibonacci [中国剩余定理+循环节]

链接

https://ac.nowcoder.com/acm/contest/889/A

题意

给定n,m,求斐波拉契数列的m次方的前n项和,答案对 1 0 9 10^9 109取模。
1 <= n <= 1 0 9 10^9 109, 1 <= m <= 1000

分析

由于 1 0 9 10^9 109是一个合数,所以逆元和二次剩余的做法就失效了。
1 0 9 10^9 109进行分解, 1 0 9 10^9 109 = 2 9 2^9 29 * 5 9 5^9 59 = 512 * 1953125
因此,我们只需要算出最终答案在对512和1953125取模下的答案,
再用中国剩余定理将两个答案合并,就能得到对 1 0 9 10^9 109取模的答案了。
对于求对512和1953125取模的答案,
我们可以分别找到斐波拉契数列在这两个模数下的循环节,
分别是768和7812500,
这也就是斐波拉契数列的m次方的前n项和的循环节,
通过循环节就能计算出最终答案在两个模数下的值了。

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
template<class T>inline void MAX(T &x,T y){if(y>x)x=y;}
template<class T>inline void MIN(T &x,T y){if(y<x)x=y;}
template<class T>inline void rd(T &x){
	x=0;char o,f=1;
	while(o=getchar(),o<48)if(o==45)f=-f;
	do x=(x<<3)+(x<<1)+(o^48);
	while(o=getchar(),o>47);
	x*=f;
}
const int P=1e9;
const int P1=512;
const int P2=1953125;
const int M=7812500;
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 n,m,F[M];
int calc(int d,int P){
	return (1ll*n/d*F[d-1]%P+F[n%d])%P;
}
int extra_gcd(int a,int b){
	while(b%P1!=a)b+=P2;
	return b;
}
int main(){
#ifndef ONLINE_JUDGE
	freopen("jiedai.in","r",stdin);
//  freopen("jiedai.out","w",stdout);
#endif
	rd(n),rd(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",extra_gcd(calc(768,P1),calc(7812500,P2)));
	return (0-0);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值