Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}