版权声明:All rights reserved. https://blog.csdn.net/qq_42814118/article/details/82148511
题
定义广义斐波那契数列为满足递推公式为
的数列。
现在给定系数
,以及该数列的前两项
,问
的值为多少。
,其它数据均
。
解
矩阵快速幂裸题,记得开 。
#include <bits/stdc++.h>
using namespace std;
#define R register
#define LL long long
LL n;
int M;
struct matrix
{
LL c[4][4];
void init()
{
memset(c,0,sizeof c);
for (R int i=1;i<=2;++i) c[i][i]=1ll;
}
friend matrix operator * (const matrix & A,const matrix & B)
{
matrix ret;
for (R int i=1;i<=2;++i)
for (R int j=1;j<=2;++j)
{
ret.c[i][j] = 0;
for (R int k=1;k<=2;++k)
ret.c[i][j] = (ret.c[i][j] + A.c[i][k] * B.c[k][j]) % M;
}
return ret;
}
friend matrix operator ^ (const matrix & A,LL B)
{
R matrix ret,bas=A;
ret.init();
while(B)
{
if(B&1) ret=ret*bas;
bas = bas*bas;
B >>= 1;
}
return ret;
}
}cha,fir;
int main()
{
scanf("%lld %lld %lld %lld %lld %d",&cha.c[1][1],&cha.c[1][2],&fir.c[2][1],&fir.c[1][1],&n,&M);
fir.c[1][2]=fir.c[2][2]=cha.c[2][2]=0;
cha.c[2][1]=1;
if(n == 1) return !printf("%lld\n",fir.c[2][1] % M);
if(n == 2) return !printf("%lld\n",fir.c[1][1] % M);
cha = cha^(n-2ll);
fir = cha*fir;
printf("%lld\n",fir.c[1][1]);
return 0;
}