feat: binpow

This commit is contained in:
2025-07-23 00:13:41 +08:00
parent 7985239605
commit 52edcb783a

View File

@@ -21,14 +21,17 @@ public class BinaryExponentiation {
} }
} }
public static BigInteger binPow(BigInteger a, BigInteger b) { public static BigInteger binPow(BigInteger base, BigInteger exponent) {
BigInteger result = BigInteger.ONE; if (exponent.compareTo(BigInteger.ZERO) < 0) {
while (b.compareTo(BigInteger.ZERO) > 0) { throw new ArithmeticException("Negative exponent");
if (b.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) {
result = result.multiply(a);
} }
a = a.multiply(a); BigInteger result = BigInteger.ONE;
b = b.divide(BigInteger.valueOf(2)); while (exponent.compareTo(BigInteger.ZERO) > 0) {
if (exponent.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) {
result = result.multiply(base);
}
base = base.multiply(base);
exponent = exponent.divide(BigInteger.valueOf(2));
} }
return result; return result;
} }