From 52edcb783af80ab51227588b5e56ac525c734eda Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Wed, 23 Jul 2025 00:13:41 +0800 Subject: [PATCH] feat: binpow --- .../java/me/hatter/math/BinaryExponentiation.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/me/hatter/math/BinaryExponentiation.java b/src/main/java/me/hatter/math/BinaryExponentiation.java index 9c0c690..62551da 100644 --- a/src/main/java/me/hatter/math/BinaryExponentiation.java +++ b/src/main/java/me/hatter/math/BinaryExponentiation.java @@ -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; - while (b.compareTo(BigInteger.ZERO) > 0) { - if (b.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) { - result = result.multiply(a); + while (exponent.compareTo(BigInteger.ZERO) > 0) { + if (exponent.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) { + result = result.multiply(base); } - a = a.multiply(a); - b = b.divide(BigInteger.valueOf(2)); + base = base.multiply(base); + exponent = exponent.divide(BigInteger.valueOf(2)); } return result; }