KatInterview

Exponentiation by Squaring with Negative Exponents

Math & Bit ManipulationAuto-graded · 23 test cases
MediumAuto-gradedMath & Bit Manipulationbinary-exponentiationmathbit-manipulation

Last updated

Compute a floating-point base raised to a signed 32-bit integer exponent in logarithmic time, including negative exponents, using repeated squaring.

Fast Integer Powers

Write a function that computes base raised to the integer power exponent, without using the built-in power operator (**), pow, or math.pow.

The base is a floating-point number and the exponent is a signed 32-bit integer, so it can be positive, zero, or negative. The function returns the result as a float.

Rules

  • A positive exponent means multiplying base by itself that many times.
  • A negative exponent means the reciprocal: base^(-m) = 1 / base^m.
  • Any base raised to the exponent 0 gives 1.0.
  • A negative base is allowed. The sign of the result follows from ordinary multiplication.
  • Multiplying base by itself |exponent| times is too slow for large exponents. Your solution should use a number of multiplications proportional to the number of bits in exponent, which is O(log |exponent|).
  • Results are floating-point values, so tiny rounding differences are expected. The standard repeated-squaring approach produces the intended values.

Constraints

  • -2^31 <= exponent <= 2^31 - 1
  • base is a finite floating-point number.
  • If exponent < 0, then base != 0.
  • The true result fits within the usual range of a double-precision float.

Examples

Example 1

Input: fast_power(2, -2)

Output: 0.25

Example 2

Input: fast_power(2, 10)

Output: 1024

Example 3

Input: fast_power(2.1, 3)

Output: 9.261000000000001

Hints

Hint 1

Write the exponent in binary. For example, x^13 = x^8 * x^4 * x^1, because 13 is 1101 in binary.

Hint 2

Keep a running 'current power' that is squared on every step (x, x^2, x^4, ...). Whenever the lowest bit of the exponent is 1, multiply that value into the result, then shift the exponent right by one.

Hint 3

Handle a negative exponent once, up front, by replacing the base with its reciprocal and negating the exponent. Python integers do not overflow, so negating -2^31 is safe.