InterviewPrepKit

Home / Coding / Math & Geometry

Pow(x, n)

medium Original β†—
Solving tips
  • An O(n) loop is hopeless with |n| up to ~2e9; use binary exponentiation (exponentiation by squaring) for O(log n).
  • Core recurrence: x^n = (x^(n/2))^2 for even n, times an extra x for odd n; compute the half once and reuse it (don't recompute).
  • Handle negative n by using 1/x with a positive exponent; note -(-2^31) overflows in fixed-width languages (Python is safe).
  • Iterative form reads n's bits: square x each step, multiply into result when the low bit is set. Remember n == 0 returns 1.0; O(log n) time, O(1) space.

Problem

Implement pow(x, n), which raises the floating-point number x to the integer power n (that is, compute x**n). The exponent n can be negative, zero, or positive.

You should not lean on a library power function β€” the task is to compute it efficiently yourself, in far fewer than n multiplications.

Examples

  • x = 2.0, n = 10 β†’ 1024.0 β€” 2 multiplied by itself ten times.
  • x = 2.1, n = 3 β†’ 9.261000000000001 β€” ordinary floating-point cube (tiny rounding is expected).
  • x = 2.0, n = -2 β†’ 0.25 β€” a negative exponent means 1 / x**|n|, so 1 / 4.

Constraints

  • -100.0 < x < 100.0
  • -2^31 <= n <= 2^31 - 1 (n fits in a 32-bit signed integer).
  • x is nonzero when n is negative; the result stays within double-precision range.
  • Because |n| can be ~2 billion, an O(n) loop is far too slow β€” you need O(log n).

Think about it first

Hint 1 Multiplying `x` by itself `n` times is O(n) β€” with `n` up to two billion, that's hopeless. Can you reuse partial results so each step roughly *doubles* the exponent you've already covered?
Hint 2 `x**n = (x**(n/2))**2` when `n` is even, and `x * (x**((n-1)/2))**2` when `n` is odd. Computing `x**(n/2)` once and squaring it halves the problem each time β€” that's O(log n) multiplications.
Hint 3 Handle a negative exponent by computing the positive power and taking the reciprocal. Watch the value `n = -2^31`: negating it overflows in fixed-width languages, though Python's big ints are safe β€” still, convert to a positive exponent carefully.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.