Java Program to Calculate Power Using Recursion
power(base, exponent) that returns 1 if exponent is 0, otherwise returns base * power(base, exponent - 1).Examples
How to Think About It
Algorithm
Code
public class PowerRecursion { public static int power(int base, int exponent) { if (exponent == 0) { return 1; } else { return base * power(base, exponent - 1); } } public static void main(String[] args) { int base = 2; int exponent = 3; System.out.println("Result: " + power(base, exponent)); } }
Dry Run
Let's trace power(2, 3) through the code
Initial call
power(2, 3) checks if exponent == 0 (false), returns 2 * power(2, 2)
Second call
power(2, 2) checks if exponent == 0 (false), returns 2 * power(2, 1)
Third call
power(2, 1) checks if exponent == 0 (false), returns 2 * power(2, 0)
Base case
power(2, 0) returns 1 because exponent == 0
Return values
power(2, 1) returns 2 * 1 = 2 power(2, 2) returns 2 * 2 = 4 power(2, 3) returns 2 * 4 = 8
| Call | Exponent | Return Value |
|---|---|---|
| power(2, 0) | 0 | 1 |
| power(2, 1) | 1 | 2 |
| power(2, 2) | 2 | 4 |
| power(2, 3) | 3 | 8 |
Why This Works
Step 1: Base case
The recursion stops when the exponent is 0, returning 1 because any number to the power 0 is 1.
Step 2: Recursive call
For exponent greater than 0, the function calls itself with exponent minus 1 to break down the problem.
Step 3: Multiplying results
Each recursive call multiplies the base by the result of the smaller problem, building up the final answer.
Alternative Approaches
public class PowerUsingMath { public static void main(String[] args) { int base = 2; int exponent = 3; double result = Math.pow(base, exponent); System.out.println("Result: " + (int)result); } }
public class PowerTailRecursion { public static int power(int base, int exponent) { return powerHelper(base, exponent, 1); } private static int powerHelper(int base, int exponent, int result) { if (exponent == 0) { return result; } else { return powerHelper(base, exponent - 1, result * base); } } public static void main(String[] args) { System.out.println("Result: " + power(2, 3)); } }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per decrement of the exponent, so it runs in linear time relative to the exponent.
Space Complexity
Each recursive call adds a new frame to the call stack, so space used is proportional to the exponent.
Which Approach is Fastest?
Using Java's built-in Math.pow() is fastest and optimized, but recursive methods are clearer for learning recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple Recursion | O(n) | O(n) | Learning recursion |
| Tail Recursion | O(n) | O(n) or optimized | Avoiding stack overflow |
| Math.pow() | O(1) | O(1) | Performance and simplicity |