InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Pow(x, n)

medium Original ↗ 00:00

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.

Do not use a built-in power function. Compute the result yourself, in far fewer than n multiplications.

Examples

  • x = 2.0, n = 101024.02 multiplied by itself ten times.
  • x = 2.1, n = 39.261000000000001 — ordinary floating-point cube (tiny rounding is expected).
  • x = 2.0, n = -20.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 is too slow. Can you reuse partial results so each step roughly doubles the exponent 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. Note `n = -2^31`: negating it overflows in fixed-width languages, though Python's big integers are safe. Convert to a positive exponent carefully.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug