我想把这个函数代码重写为Java中的BigInteger
类:
static int power(int x, int y, int p)
{
int res = 1; // Initialize result
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res % p;
}
我试着写了下面的代码:
static BigInteger power(BigInteger x, BigInteger y, BigInteger p) {
BigInteger res = BigInteger.ONE; // Initialize result
while (y.compareTo(BigInteger.ZERO) == 1) {
// If y is odd, multiply x with result
if ((y.and(BigInteger.ONE)) != BigInteger.ZERO)
res = res.multiply(x);
// y must be even now
y = y.shiftRight(1); // y = y/2
x = x.multiply(x); // Change x to x^2
}
return res.mod(p);
}
但当我测试输入"功率(2,5,13)"时,输出是11,然而,正确答案是6.
我判断了几次我写的代码,但没有发现问题.你能帮我输出正确的答案代码吗?