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) - Binary Exponentiation INPUT x = 2.0 (base) n = 10 (exponent) Calculate: 2^10 Binary of 10: 1 8 0 4 1 2 0 1 10 = 8 + 2 = 1010 (binary) 2^10 = 2^8 * 2^2 Naive: O(n) multiplications 10 operations for n=10 ALGORITHM STEPS 1 Initialize result=1, base=x, exp=|n| 2 While exp > 0 Check if exp is odd 3 If odd: result *= base Square base, halve exp 4 Return result If n negative: 1/result Iterations for 2^10 exp base result action 10 2 1 even 5 4 4 odd* 2 16 4 even 1 256 1024 odd* 0 - 1024 done Only 4 iterations! O(log n) FINAL RESULT Output: 1024.0 Verification: 2^10 = 2^8 × 2^2 = 256 × 4 = 1024 OK Complexity: Time: O(log n) Space: O(1) log2(10) ~ 4 iterations Key Insight: Binary exponentiation exploits the fact that any exponent can be represented in binary. Instead of n multiplications, we only need log(n) by repeatedly squaring the base and multiplying into result only when the current bit is 1. Example: 2^10 = 2^(8+2) = 2^8 × 2^2 TutorialsPoint - Pow(x, n) | Binary Exponentiation (Fast Power)
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