Pow(x, n) - Problem

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

You need to handle both positive and negative exponents efficiently.

Note: Your solution should be more efficient than the naive approach of multiplying x by itself n times.

Input & Output

Example 1 — Positive Exponent
$ Input: x = 2.0, n = 10
Output: 1024.0
💡 Note: 2^10 = 1024. Using binary exponentiation: 2^10 = (2^5)^2 = 32^2 = 1024
Example 2 — Negative Exponent
$ Input: x = 2.1, n = -2
Output: 0.22676
💡 Note: 2.1^(-2) = 1/(2.1^2) = 1/4.41 ≈ 0.22676
Example 3 — Zero Exponent
$ Input: x = 2.0, n = 0
Output: 1.0
💡 Note: Any number raised to power 0 equals 1

Constraints

  • -100.0 < x < 100.0
  • -231 ≤ n ≤ 231-1
  • -104 ≤ xn ≤ 104

Visualization

Tap to expand
Pow(x, n): Calculate x^n EfficientlyInputx = 2.0, n = 10Binary ExponentiationO(log n) instead of O(n)Output1024.0Naive Approach: 2×2×2×2×2×2×2×2×2×2 (10 steps)Smart Approach: 2^10 = (2^5)^2 = (2×(2^2)^2)^2 (4 steps)Key Insight: Use x^n = (x^(n/2))^2Halve the exponent, square the result - reduces complexity from O(n) to O(log n)
Understanding the Visualization
1
Input
Base x and exponent n
2
Process
Use binary exponentiation instead of repeated multiplication
3
Output
x raised to the power n
Key Takeaway
🎯 Key Insight: Binary exponentiation reduces O(n) to O(log n) by repeatedly halving the exponent
Asked in
Facebook 35 Google 30 LinkedIn 25 Amazon 20
120.0K Views
High Frequency
~15 min Avg. Time
4.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen