how to write a recursive function which can calculate for negative value of power
Calculate the 2power n where n can be negative
@bhaskarkumarindia_194428d5e21261da Here’s how you can write a recursive function in Java to calculate the negative power of a number without using the reciprocal directly:
public class PowerCalculation {
public static double power(double base, int exp) {
// Base case
if (exp == 0) {
return 1;
}
// Recursive case for negative exponent
else if (exp < 0) {
return (1 / base) * power(base, exp + 1);
}
// Recursive case for positive exponent
else {
return base * power(base, exp - 1);
}
}
public static void main(String[] args) {
System.out.println(power(2, -3)); // Output: 0.125
}
}
Explanation:
-
Base Case : When
exp
is 0, the function returns 1, as any number to the power of 0 is 1. -
Negative Exponent Case : When
exp
is negative, the function reduces the exponent by 1 (i.e.,exp + 1
) and multiplies the result by1/base
. -
Positive Exponent Case : When
exp
is positive, it multiplies the base by the result of the recursive call withexp - 1
.
This Java method will compute the negative power of a number without explicitly using the reciprocal at the start. Instead, it computes the inverse of the base during the recursive steps.