Power Function
Recursion
📋 Problem Statement
Write a recursive function power(x, n) that calculates . Input: → Output: 1024. You must use recursion and must not use the ** operator. Naive multiplication is — achieve .
💡 Intuition
Exponentiation by squaring: when is even. This halves the problem at each step, giving . For odd : . This mirrors the binary search halving principle, applied to computation.
🔧 Approach
- Base case: if , return 1 (by definition ).
- Recursively compute .
- If is even: return .
- If is odd: return .
⚡ Complexity Analysis
Time
where is the exponent — we halve the exponent with each recursive call
Space
for the recursion stack
⚠️ Common Mistakes
- Using a simple loop (, times) — , too slow for
- Computing
power(base, exp // 2)twice instead of storing the result — turns into - Not handling as the base case
- Forgetting the odd exponent case: , not just
🎯 Final Thoughts
Fast exponentiation (binary exponentiation) reduces multiplications to about 20. It underpins modular exponentiation in RSA cryptography, matrix exponentiation for Fibonacci, and competitive programming. "Compute half, then combine" is the essence of divide and conquer.