With Clear Diagrams + Recursive & Iterative Methods (C#)
When solving Pow(x, n) in interviews (Google, Meta, etc.), a
brute-force solution is NOT enough.
The naive way:
x * x * x * x * ... (n times)
This takes O(n) time.
But we can do better.
We can solve it in:
O(log n)
Let's understand this deeply --- visually and line-by-line.
๐ง The Key Mathematical Insight
If n is EVEN:
x^n = (x^(n/2))ยฒ
Example:
2^8
= (2^4)ยฒ
= (16)ยฒ
= 256
Why?
Because:
2^8 = 2ร2ร2ร2ร2ร2ร2ร2
= (2ร2ร2ร2) ร (2ร2ร2ร2)
= 2^4 ร 2^4
If n is ODD:
x^n = (x^((n-1)/2))ยฒ ร x
Example:
2^9
= 2 ร 2^8
= 2 ร (2^4)ยฒ
We remove one x to make the exponent even.
๐ Why This Is Faster
Instead of reducing:
n โ n-1 โ n-2 โ ...
We reduce:
n โ n/2 โ n/4 โ n/8 โ ...
So recursion depth becomes:
O(log n)
๐ Recursive Method (C#)
public class Solution {
public double MyPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
return FastPow(x, N);
}
private double FastPow(double x, long n) {
if (n == 0) return 1;
double half = FastPow(x, n / 2);
if (n % 2 == 0)
return half * half;
else
return half * half * x;
}
}
๐ Recursive Flow Diagram (Example: 2^13)
FastPow(2,13)
โ
FastPow(2,6)
โ
FastPow(2,3)
โ
FastPow(2,1)
โ
FastPow(2,0)
Now it builds back up:
2^0 = 1
2^1 = 1ร1ร2 = 2
2^3 = 2ร2ร2 = 8
2^6 = 8ร8 = 64
2^13 = 64ร64ร2 = 8192
โ Final Answer: 8192
๐ง What Happens in Memory (Call Stack)
At deepest recursion:
FastPow(2,13)
FastPow(2,6)
FastPow(2,3)
FastPow(2,1)
FastPow(2,0)
Then it unwinds upward.
Maximum stack depth:
logโ(13) โ 4 levels
โก Iterative Method (More Interview Friendly)
This avoids recursion entirely.
public double MyPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double result = 1;
while (N > 0) {
if ((N & 1) == 1) {
result *= x;
}
x *= x;
N >>= 1;
}
return result;
}
๐ Iterative Flow (2^13)
Binary of 13:
13 = 1101โ
We process bits from right to left:
| Step | N | Action | x becomes |
|---|---|---|---|
| 1 | 13 (odd) | result *= x | xยฒ |
| 2 | 6 | skip | xโด |
| 3 | 3 (odd) | result *= x | xโธ |
| 4 | 1 (odd) | result *= x | xยนโถ |
Final result = 8192
โฑ Complexity
| Method | Time Complexity | Space Complexity |
|---|---|---|
| Recursive | O(log n) | O(log n) |
| Iterative | O(log n) | O(1) |
๐ฏ Final Takeaways
- Never multiply
xn times. - Use divide-and-conquer.
- Always convert
ntolongto avoid overflow. - Prefer iterative version in interviews.
If this helped you understand recursion better, try implementing it
yourself without looking at the solution!
Top comments (0)