forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPowerUsingRecursion.java
More file actions
44 lines (37 loc) · 1.06 KB
/
PowerUsingRecursion.java
File metadata and controls
44 lines (37 loc) · 1.06 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
package com.thealgorithms.maths;
/**
* calculate Power using Recursion
* @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) {
// Handle negative exponent: a^-n = 1 / (a^n)
if (exponent < 0) {
return 1.0 / power(base, -exponent);
}
// Base cases
if (exponent == 0) {
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;
}
// If exponent is odd: a^n = a * a^(n-1)
return base * power(base, exponent - 1);
}
}