模数指数溢出

时间:2015-06-05 15:55:59

标签: java recursion overflow

public class Solution {
    public int pow(int A,int B,int d)
{
    if(A<0){ A=A+d;}
    if (B==0)
    {
        if(A==0){return 0;}
        return 1;
    }
    else if(B%2==0)
    {
        int y=pow(A,B/2,d);
        return (y*y)%d;
    }
    else
    {
        return (A%d*pow(A,B-1,d))%d;
    }
}

}

我的代码溢出了, 答:71045970 B:41535484 电话:64735492

我的代码给出了o / p:-17412928 预期o / p:20805472 哪里出错?

有人可以修改我的代码吗?

2 个答案:

答案 0 :(得分:1)

请试试这个

public int Mod(int a, int b, int c) {
    if(b==0){
        if(a==0) return 0;
        else
        return 1;
    }
    else if(b%2==0){
        long y=Mod(a,b/2,c);

        return (int)(((long)(y*y))%(long)c);
    }else{
        int k=a%c;
        if(k<0){
            k+=c;
        }
        return (int)(((long)((long)k * (long)Mod(a,b-1,c)))%(long)c);
    }
}

答案 1 :(得分:0)

BigInteger作为modPow方法,可以为您轻松完成此任务。

没有给出您的预期结果,但给出了不同的结果:

public int pow(int a, int b, int mod) {
    if (a < 0) {
        a = a + mod;
    }
    if (b == 0) {
        if (a == 0) {
            return 0;
        }
        return 1;
    } else if (b % 2 == 0) {
        int y = pow(a, b / 2, mod);
        return (y * y) % mod;
    } else {
        return (a % mod * pow(a, b - 1, mod)) % mod;
    }
}

public int bigPow(int a, int b, int mod) {
    return BigInteger.valueOf(a).modPow(BigInteger.valueOf(a), BigInteger.valueOf(mod)).intValue();
}

private void test(int a, int b, int mod) {
    System.out.println("Old - modPow(" + a + "," + b + "," + mod + ") = " + pow(a, b, mod));
    System.out.println("New - modPow(" + a + "," + b + "," + mod + ") = " + bigPow(a, b, mod));
}

public void test() {
    test(71045970, 41535484, 64735492);
}

打印

Old - modPow(71045970,41535484,64735492) = -17412928
New - modPow(71045970,41535484,64735492) = 44382800

如果你实际上没有找modPow(现在看起来很可能),那么使用BigInteger复制你的算法是一个粗略的尝试。

public BigInteger bigPow(BigInteger a, BigInteger b, BigInteger mod) {
    if (a.compareTo(BigInteger.ZERO) < 0) {
        a = a.add(mod);
    }
    if (b.compareTo(BigInteger.ZERO) == 0) {
        if (a.compareTo(BigInteger.ZERO) == 0) {
            return BigInteger.ZERO;
        }
        return BigInteger.ONE;
    } else if (!b.testBit(0)) {
        BigInteger y = bigPow(a, b.shiftRight(1), mod);
        return y.multiply(y).mod(mod);
    } else {
        return a.mod(mod).multiply(bigPow(a, b.subtract(BigInteger.ONE), mod));
    }
}

现在给出了预期的答案。

Old - modPow(71045970,41535484,64735492) = -17412928
New - modPow(71045970,41535484,64735492) = 20805472