Repository navigation
Expand file tree
/
Copy pathPowerUsingRecursion.java
More file actions
47 lines (42 loc) · 1.53 KB
/
Copy pathPowerUsingRecursion.java
File metadata and controls
47 lines (42 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.thealgorithms.maths;
/**
* Utility class to calculate power using recursion.
*
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public final class PowerUsingRecursion {
private PowerUsingRecursion() {
}
/**
* Calculates the power of a base raised to an exponent using recursion.
*
* @param base the base value
* @param exponent the power to raise the base to
* @return the result of base^exponent
* @throws ArithmeticException if base is 0 and exponent is negative
*/
public static double power(double base, int exponent) {
// Base case: anything raised to the power of 0 is 1
if (exponent == 0) {
return 1;
}
// Handle negative exponents using the reciprocal of base: base^(-e) = (1 / base)^e
if (exponent < 0) {
if (base == 0.0) {
throw new ArithmeticException("Base cannot be 0 with a negative exponent.");
}
if (exponent == Integer.MIN_VALUE) {
double reciprocal = 1.0 / base;
return reciprocal * power(reciprocal, -(exponent + 1));
}
return power(1.0 / base, -exponent);
}
// Recursive case: divide-and-conquer for even exponents to reduce depth to O(log n)
if (exponent % 2 == 0) {
double half = power(base, exponent / 2);
return half * half;
}
// Recursive case for odd exponents
return base * power(base, exponent - 1);
}
}