广义斐波那契数列 / 矩阵快速幂

版权声明:All rights reserved. https://blog.csdn.net/qq_42814118/article/details/82148511

定义广义斐波那契数列为满足递推公式为 a n = p a n 1 + q a n 2 n 2 的数列。
现在给定系数 p , q ,以及该数列的前两项 a 1 a 2 ,问 a n % m 的值为多少。
n 10 13 ,其它数据均 10 10

矩阵快速幂裸题,记得开 l o n g l o n g

#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;
}

猜你喜欢

转载自blog.csdn.net/qq_42814118/article/details/82148511