Algorithm LogbookAlgorithm Logbook

Power Function

Recursion

📋 Problem Statement

Write a recursive function power(x, n) that calculates xnx^n. Input: x=2,n=10x = 2, n = 10 → Output: 1024. You must use recursion and must not use the ** operator. Naive multiplication is O(N)O(N) — achieve O(logN)O(\log N).

💡 Intuition

Exponentiation by squaring: xn=(xn/2)2x^n = (x^{n/2})^2 when nn is even. This halves the problem at each step, giving O(logN)O(\log N). For odd nn: xn=x(xn/2)2x^n = x \cdot (x^{\lfloor n/2 \rfloor})^2. This mirrors the binary search halving principle, applied to computation.

🔧 Approach

  1. Base case: if n=0n = 0, return 1 (by definition x0=1x^0 = 1).
  2. Recursively compute half=power(base,n/2)\text{half} = \text{power}(\text{base}, \lfloor n/2 \rfloor).
  3. If nn is even: return half2\text{half}^2.
  4. If nn is odd: return base×half2\text{base} \times \text{half}^2.

Complexity Analysis

Time

O(logN)O(\log N) where NN is the exponent — we halve the exponent with each recursive call

Space

O(logN)O(\log N) for the recursion stack

⚠️ Common Mistakes

  • Using a simple loop (x×x×x \times x \times \cdots, nn times) — O(N)O(N), too slow for n=106n = 10^6
  • Computing power(base, exp // 2) twice instead of storing the result — turns O(logN)O(\log N) into O(N)O(N)
  • Not handling n=0n = 0 as the base case
  • Forgetting the odd exponent case: x5=x(x2)2x^5 = x \cdot (x^2)^2, not just (x2)2(x^2)^2

🎯 Final Thoughts

Fast exponentiation (binary exponentiation) reduces 10610^6 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.