DSA problem
Power of a Number Using Recursion
Given two integers base and exp, compute base^exp (base raised to the power exp) using recursion.
The naive recursive approach computes power(base, exp) = base * power(base, exp - 1) with base case power(base, 0) = 1, which runs in O(exp) time. The optimized approach uses exponentiation by squaring: if exp is even, power(base, exp) = power(base * base, exp / 2); if exp is odd, power(base, exp) = base * power(base, exp - 1). This reduces the time to O(log exp) - a massive improvement for large exponents.
Exponentiation by squaring powers modular exponentiation (critical in RSA encryption), matrix exponentiation (computing Fibonacci numbers in O(log N)), and countless competitive-programming problems. It is a first taste of divide-and-conquer optimization.
Examples
base = 2, exp = 101024base = 3, exp = 5243base = 7, exp = 01Constraints
- 0 <= base <= 100
- 0 <= exp <= 30
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.