快速幂和模除

  1. 递归快速幂
    思想很简单, a 9 = a ∗ a 8 , a 8 = a 4 ∗ a 4 a^9=a*a^8,a^8=a^4*a^4 a9=aa8,a8=a4a4
public static int fastPower1(int a, int b){
        if(b == 0)
            return 1;
        if(b%2 == 1)
            return a*fastPower1(a,b - 1);
        else{
            int temp = fastPower1(a,b/2);
            return temp*temp;
        }
    }
  1. 非递归快速幂
    a 1 5 ( 10 ) = a 111 1 ( 2 ) = a 100 0 ( 2 ) ∗ a 10 0 ( 2 ) ∗ a 1 0 ( 2 ) ∗ a 1 ( 2 ) a^{15_{(10)}}=a^{1111_{(2)}}=a^{1000_{(2)}}*a^{100_{(2)}}*a^{10_{(2)}}*a^{1_{(2)}} a15(10)=a1111(2)=a1000(2)a100(2)a10(2)a1(2)并且 a 100 0 ( 2 ) = a 10 0 ( 2 ) ∗ a 10 0 ( 2 ) a^{1000_{(2)}}=a^{100_{(2)}}*a^{100_{(2)}} a1000(2)=a100(2)a100(2)
 public static int fastPower2(int a, int b){
        int ans = a; int result = 1;
        while(b > 0){
            if((b&1) == 1){
                result = result*ans;
            }
            ans = ans*ans;
            b = b>>1;
        }
        return result;
    }
  1. 递归快速幂模除
    ( a ∗ b ) % c = ( ( a % c ) ∗ ( b % c ) ) % c (a*b)\%c=((a\%c)*(b\%c))\%c (ab)%c=((a%c)(b%c))%c
 public static int fastPowerMod1(int a, int b, int mod){
        if(b == 0)
            return 1;
        if(b%2 == 1)
        	//加或者乘的时候需要防溢出
            return (int)(((long)(a*fastPower1(a,b - 1)))%mod);
        else{
            int temp = fastPower1(a,b/2)%mod;
            return (int) (((long)temp*temp)%mod);
        }
    }
  1. 非递归快速幂模除
public static int fastPowerMod2(int a, int b, int mod){
        int ans = a; int result = 1;
        while(b > 0){
            if((b&1) == 1){
                result = (int)(((long)(result*ans))%mod);
            }
            ans = (int)((long)(ans*ans))%mod;
            b = b>>1;
        }
        return result;
    }
  1. 矩阵快速幂
public static int[][] fastMatrixPowerMod(int[][] a, int b, int mod){
        int[][] result = {{1,0},{0,1}}; int[][] ans = a;
        while(b > 0){
            if((b&1) > 0)
                result = matrixPowerMod(result,ans,mod);
            ans = matrixPowerMod(ans, ans, mod);
            b = b>>1;
        }
        return result;
    }

    public static int[][] matrixPowerMod(int[][] a, int[][] b, int mod){
        int rows, columns;
        rows = a.length; columns=a[0].length;
        int[][] c = new int[rows][columns];
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < columns; j++)
                for(int k = 0; k < columns; k++)
                    c[i][j] = (int)(((long)c[i][j] + (long)a[i][k]*b[k][j])%mod);
        return c;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值