Pow(x, n) - Problem
Power Function Implementation
You need to implement your own version of the mathematical power function that calculates xn (x raised to the power of n).
Goal: Given a base number
Key Challenges:
• Handle negative exponents (fractional results)
• Handle large exponents efficiently
• Deal with edge cases like x=0, n=0
• Avoid timeout for large values of n
Example:
You need to implement your own version of the mathematical power function that calculates xn (x raised to the power of n).
Goal: Given a base number
x and an exponent n, return the result of xn.Key Challenges:
• Handle negative exponents (fractional results)
• Handle large exponents efficiently
• Deal with edge cases like x=0, n=0
• Avoid timeout for large values of n
Example:
pow(2, 10) should return 1024, and pow(2, -2) should return 0.25. Input & Output
example_1.py — Basic Power
$
Input:
x = 2.0, n = 10
›
Output:
1024.0
💡 Note:
2^10 = 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 1024
example_2.py — Negative Exponent
$
Input:
x = 2.1, n = 3
›
Output:
9.261
💡 Note:
2.1^3 = 2.1 × 2.1 × 2.1 = 9.261
example_3.py — Negative Exponent
$
Input:
x = 2.0, n = -2
›
Output:
0.25
💡 Note:
2^(-2) = 1/(2^2) = 1/4 = 0.25
Visualization
Tap to expand
Understanding the Visualization
1
Base Case
If n = 0, return 1 (any number^0 = 1)
2
Divide
Compute half_power = x^(n/2) recursively
3
Square
Square the half_power to get x^n
4
Handle Odd
If n is odd, multiply by one extra x
Key Takeaway
🎯 Key Insight: By using the mathematical property x^n = (x^(n/2))^2, we can reduce the problem size by half at each step, achieving logarithmic time complexity instead of linear!
Time & Space Complexity
Time Complexity
O(log n)
We divide n by 2 at each recursive step, so we make log n recursive calls
⚡ Linearithmic
Space Complexity
O(log n)
Recursion depth is log n due to the call stack
⚡ Linearithmic Space
Constraints
- -100.0 < x < 100.0
- -231 ≤ n ≤ 231-1
- -104 ≤ xn ≤ 104
- Important: Your solution must handle negative exponents correctly
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code