深夜敲模板_1——快速幂 && 矩阵的快速幂

快速幂:

///a^n%m
int quickpow(int a,int n,int m){
    int ans=1;
    while(n){
        if(n&1) ans = (ans*a)%m;
        a = (a*a)%m;
        n>>=1;
    }
}

矩阵的快速幂:

///用结构体保存一个矩阵
struct Matrix{
    int mat[N][N];
    ///两个矩阵乘法
    Matrix operator *(const Matrix& a) const{
        Matrix c;
        memset(c.mat,0,sizeof(c.mat));
        for(int i=0;i<N;i++){
            for(j=0;j<N;j++){
                for(int k=0;k<N;k++){
                    c.mat[i][j]+=mat[i][k]*a.mat[k][j];
                }
            }
        }
        return c;
    }
    ///矩阵的幂,用二分的思想写,就是快速幂算法
    Matrix operator ^(int n) const{
        Matrix c;
        ///初始化为单位矩阵
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                c.mat[i][j]=(i==j);
            }
        }
        ///就是快速幂
        Matrix a = *this;///毕竟直接敲的模板,没运行就写上去了,发现这里少了一个*号
        while(n)
        {
            if(n%2) c=c*a;
            a=a*a;
            n=n>>1;
        }
        return c;
    }
};


原文地址:https://www.cnblogs.com/hqwhqwhq/p/4555885.html