Skip to content

Commit c8b37f6

Browse files
committed
Optimize power() using exponentiation by squaring (O(log n)) - Vinayak
1 parent a008cc2 commit c8b37f6

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,44 @@
22

33
/**
44
* calculate Power using Recursion
5-
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
5+
* @author Vinayak (https://github.com/Vinayak-v12)
66
*/
77

88
public final class PowerUsingRecursion {
99
private PowerUsingRecursion() {
1010
}
1111

12+
/**
13+
* Computes base raised to the given exponent.
14+
*
15+
* @param base the number to be raised
16+
* @param exponent the power (can be negative)
17+
* @return base^exponent
18+
*/
19+
1220
public static double power(double base, int exponent) {
13-
// Base case: anything raised to the power of 0 is 1
21+
22+
// Handle negative exponent: a^-n = 1 / (a^n)
23+
if (exponent < 0) {
24+
return 1.0 / power(base, -exponent);
25+
}
26+
27+
// Base cases
1428
if (exponent == 0) {
15-
return 1;
29+
return 1.0;
30+
}
31+
if (exponent == 1) {
32+
return base;
33+
}
34+
35+
// Exponentiation by Squaring
36+
// If exponent is even: a^n = (a^(n/2))^2
37+
if (exponent % 2 == 0) {
38+
double half = power(base, exponent / 2);
39+
return half * half;
1640
}
1741

18-
// Recursive case: base ^ exponent = base * base ^ (exponent - 1)
19-
// Recurse with a smaller exponent and multiply with base
42+
// If exponent is odd: a^n = a * a^(n-1)
2043
return base * power(base, exponent - 1);
2144
}
2245
}

0 commit comments

Comments
 (0)