我试图在BigIntegers上实现modExp运算符(我知道它已经存在,但它仅适用于演示文稿)。
所以我跟随维基百科上发现的伪代码:
function modular_pow(base, exponent, modulus)
if modulus = 1 then return 0
Assert :: (modulus - 1) * (modulus - 1) does not overflow base
result := 1
base := base mod modulus
while exponent > 0
if (exponent mod 2 == 1):
result := (result * base) mod modulus
exponent := exponent >> 1
base := (base * base) mod modulus
return result
所以这就是我在Java中提出的:
static BigInteger modExp(BigInteger x, BigInteger y, BigInteger m)
{
if(m.equals(BigInteger.ONE))
return BigInteger.ZERO;
BigInteger result = BigInteger.ONE;
x = x.mod(m);
while(y.compareTo(BigInteger.ZERO) > 0){
if (y.mod(TWO).equals(BigInteger.ONE)){
result = (result.multiply(x)).mod(m);
}
y = y.shiftRight(1);
x = (x.multiply(x).mod(m));
}
return result;
}
问题:在这种情况下,用2除法替换右移可以吗?