Vision_MATH_快速幂||矩阵快速幂

///定义:
/*
    快速幂就是快速算底数的n次幂。其时间复杂度为 O(logN), 与朴素的O(N)相比效率有了极大的提高。
    也就是求A^B%mod的值,其中A可以是数字也可以是矩阵(矩阵快速幂)
*/


///代码:

/*
**name:快速幂
**function:求解a^b%mod的值(mod*mod不会爆long long的情况)
**输入参数:a,b,mod
**输出参数:a^b%mod
*/
typedef long long LL;
LL Q_pow(LL a,LL b,LL mod){
    LL ans = 1;
    while(b){
        if(b&1)ans=ans*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}


/*
**name:快速幂
**function:求解a^b%mod的值(mod*mod会爆long long的情况)
**输入参数:a,b,mod
**输出参数:a^b%mod
*/
typedef long long LL;
LL modular_multi(LL a, LL b, LL c) {/// a * b % c
    LL res, temp;
    res = 0, temp = a % c;
    while (b) {
        if (b & 1) {
            res += temp;
            if (res >= c) {
                res -= c;
            }
        }
        temp <<= 1;
        if (temp >= c) {
            temp -= c;
        }
        b >>= 1;
    }
    return res;
}
LL modular_exp(LL a, LL b, LL mod) { ///a ^ b % mod 改成mod_pow就不行,中间发生了溢出,还是这个模板靠谱
    LL res, temp;
    res = 1 % mod, temp = a % mod;
    while (b) {
        if (b & 1) {
            res = modular_multi(res, temp, mod);
        }
        temp = modular_multi(temp, temp, mod);
        b >>= 1;
    }
    return res;
}
/*
**name:矩阵快速幂
**function:求解A^b%mod的值(A为矩阵)
*/

struct Matrix
{
    int a[2][2];//矩阵大小根据需求修改
    Matrix()
    {
        memset(a,0,sizeof(a));
    }
    void init()
    {
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                a[i][j]=(i==j);
    }
    Matrix operator + (const Matrix &B)const
    {
        Matrix C;
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                C.a[i][j]=(a[i][j]+B.a[i][j])%MOD;
        return C;
    }
    Matrix operator * (const Matrix &B)const
    {
        Matrix C;
        for(int i=0;i<2;i++)
            for(int k=0;k<2;k++)
                for(int j=0;j<2;j++)
                    C.a[i][j]=(C.a[i][j]+1LL*a[i][k]*B.a[k][j])%MOD;
        return C;
    }
    Matrix operator ^ (const int &t)const
    {
        Matrix A=(*this),res;
        res.init();  ///矩阵的单位矩阵初始化
        int p=t;
        while(p)
        {
            if(p&1)res=res*A;
            A=A*A;
            p>>=1;
        }
        return res;
    }
};
int main(){
    Matrix A,ans;
    ans =  A^b;
    return;
}




///扩展:NULL



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值