Implement Fast Power with Negative Exponents
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Implement `fast_power(x, n)` without calling a built-in exponentiation routine. `n` is a signed 32-bit integer and may be negative.
Return `x` raised to the power `n`. A zero exponent returns `1`. For a negative exponent, compute the reciprocal of the corresponding positive power. Inputs for which the mathematical result is undefined, such as zero raised to a negative exponent, are outside this task.
Your algorithm should use `O(log |n|)` multiplications and must remain correct when `n` is the minimum signed 32-bit integer, whose positive magnitude cannot be represented in the same type.
For example, `fast_power(2, -3)` returns `0.125`.
```hint Halve the exponent
After separating the sign, square the base while repeatedly halving the exponent. An odd exponent contributes the current base to the result.
```
```hint Widen before negating
Convert the exponent to a wider signed type before taking the magnitude so the minimum 32-bit value does not overflow.
```
### Discussion Extensions
- Compare recursive exponentiation by squaring with an iterative implementation.
- Explain the time complexity of both versions and the extra stack space used by recursion.
Quick Answer: Implement exponentiation by squaring for signed exponents without using a built-in power function. Handle zero and negative exponents, including the minimum 32-bit integer, while achieving logarithmic multiplication count.
Implement fast_power(x, n) without a built-in exponentiation routine. The exponent n is a signed 32-bit integer. Return x raised to n, using reciprocal powers when n is negative and returning 1 when n is zero. Zero raised to a negative exponent is excluded.
Constraints
- x is a finite number from -2,147,483,648 through 2,147,483,648.
- -2,147,483,648 <= n <= 2,147,483,647.
- The mathematical result for each input is finite and representable as a double.
- Inputs with x = 0 and n < 0 are excluded.
- A built-in power or exponentiation routine may not be used.
Examples
Input: (2.0, 10)
Expected Output: 1024.0
Explanation: A positive even exponent is built by repeated squaring.
Input: (2.0, -3)
Expected Output: 0.125
Explanation: A negative exponent returns the reciprocal power.
Hints
- Separate the exponent sign first; a negative exponent can be handled by inverting the base.
- Square the base while halving a nonnegative exponent, multiplying the result only for odd bits.
- Convert n to a wider signed type before negating the minimum 32-bit value.