feat: binpow
This commit is contained in:
@@ -21,14 +21,17 @@ public class BinaryExponentiation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BigInteger binPow(BigInteger a, BigInteger b) {
|
public static BigInteger binPow(BigInteger base, BigInteger exponent) {
|
||||||
|
if (exponent.compareTo(BigInteger.ZERO) < 0) {
|
||||||
|
throw new ArithmeticException("Negative exponent");
|
||||||
|
}
|
||||||
BigInteger result = BigInteger.ONE;
|
BigInteger result = BigInteger.ONE;
|
||||||
while (b.compareTo(BigInteger.ZERO) > 0) {
|
while (exponent.compareTo(BigInteger.ZERO) > 0) {
|
||||||
if (b.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) {
|
if (exponent.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) {
|
||||||
result = result.multiply(a);
|
result = result.multiply(base);
|
||||||
}
|
}
|
||||||
a = a.multiply(a);
|
base = base.multiply(base);
|
||||||
b = b.divide(BigInteger.valueOf(2));
|
exponent = exponent.divide(BigInteger.valueOf(2));
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user