diff --git a/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java b/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java index 93c8252ab929..e87038483ff2 100644 --- a/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java +++ b/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java @@ -2,21 +2,43 @@ /** * calculate Power using Recursion - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Vinayak (https://github.com/Vinayak-v12) */ public final class PowerUsingRecursion { private PowerUsingRecursion() { } + /** + * Computes base raised to the given exponent. + * + * @param base the number to be raised + * @param exponent the power (can be negative) + * @return base^exponent + */ public static double power(double base, int exponent) { - // Base case: anything raised to the power of 0 is 1 + + // Handle negative exponent: a^-n = 1 / (a^n) + if (exponent < 0) { + return 1.0 / power(base, -exponent); + } + + // Base cases if (exponent == 0) { - return 1; + return 1.0; + } + if (exponent == 1) { + return base; + } + + // Exponentiation by Squaring + // If exponent is even: a^n = (a^(n/2))^2 + if (exponent % 2 == 0) { + double half = power(base, exponent / 2); + return half * half; } - // Recursive case: base ^ exponent = base * base ^ (exponent - 1) - // Recurse with a smaller exponent and multiply with base + // If exponent is odd: a^n = a * a^(n-1) return base * power(base, exponent - 1); } } diff --git a/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java b/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java index 705cc6672818..16f779eb965f 100644 --- a/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java +++ b/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java @@ -6,15 +6,23 @@ /** * Test case for Power using Recursion - * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + * @author Vinayak (https://github.com/Vinayak-v12) */ class PowerUsingRecursionTest { @Test void testPowerUsingRecursion() { - assertEquals(32.0, PowerUsingRecursion.power(2.0, 5)); - assertEquals(97.65625, PowerUsingRecursion.power(2.5, 5)); - assertEquals(81, PowerUsingRecursion.power(3, 4)); + // exponent = 0 + assertEquals(1.0, PowerUsingRecursion.power(5.0, 0)); + + // exponent = 1 + assertEquals(5.0, PowerUsingRecursion.power(5.0, 1)); + + // negative exponent + assertEquals(0.25, PowerUsingRecursion.power(2.0, -2)); + + // another negative exponent + assertEquals(0.5, PowerUsingRecursion.power(2.0, -1)); } }