【题解】
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);
}