← Questions
Implement pow(x, n) with fast exponentiation
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Compute x raised to an integer power n, which may be negative, using O(log |n|) multiplications instead of multiplying n times.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
my_pow(x: float, n: int) -> float— no use of the language's power operator or library.
Example
my_pow(2.0, 10) -> 1024.0
my_pow(2.1, 3) -> 9.261 (up to floating-point rounding)
my_pow(2.0, -2) -> 0.25
my_pow(5.0, 0) -> 1.0
my_pow(-2.0, 3) -> -8.0
Constraints
-
-100 < x < 100;nis a 32-bit signed integer, soncan be-2^31. -
xis not zero whennis negative.
Clarifying questions
- Can
nbe negative, and what aboutn = 0orx = 0? - How should
n = -2^31be handled in a language where-noverflows? - What precision is expected?
- Recursive or iterative?
What a strong answer covers
- Exponentiation by squaring:
x^n = (x^(n/2))^2, timesxwhennis odd.O(log |n|)time. - The iterative version over the bits of
n: square the base each step, multiply into the result when the low bit is set;O(1)space. - Negative exponents: compute with
|n|and take the reciprocal; widennto 64 bits first so-(-2^31)doesn't overflow. - Edge cases:
n = 0,x = 1or-1,x = 0, very large|n|where the result underflows to 0. - Tests against a reference on a table of cases.
Follow-ups
- Modular exponentiation
x^n mod mfor integers. - Raise a matrix to a power (and compute Fibonacci numbers in
O(log n)). - Compute the integer square root without library calls.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
