The power of Fibonacci [中國剩餘定理+循環節]

鏈接

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

題意

給定n,m,求斐波拉契數列的m次方的前n項和,答案對10910^9取模。
1 <= n <= 10910^9, 1 <= m <= 1000

分析

由於10910^9是一個合數,所以逆元和二次剩餘的做法就失效了。
10910^9進行分解,10910^9 = 292^9 * 595^9 = 512 * 1953125
因此,我們只需要算出最終答案在對512和1953125取模下的答案,
再用中國剩餘定理將兩個答案合併,就能得到對10910^9取模的答案了。
對於求對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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章