KatInterview

Integer Power via Repeated Squaring

Math & Bit ManipulationAuto-graded · 25 test cases
MediumAuto-gradedMath & Bit Manipulationbinary-exponentiationfloating-pointedge-cases

Last updated

Compute a float raised to a signed 32-bit integer power in logarithmic time and constant space, handling negative exponents, zero bases and the most negative exponent.

Integer Power

Write a function power_by_squaring(base, exponent) that returns base raised to the integer power exponent, as a floating-point number.

You may not use the built-in power operator or pow, and you may not use recursion. The solution should take time logarithmic in |exponent| and use only a constant amount of extra memory.

Rules

  • exponent == 0 returns 1.0 for every base, including 0.0.
  • A positive exponent means the usual repeated multiplication.
  • A negative exponent means the reciprocal: base ** exponent == 1 / (base ** -exponent).
  • base == 0.0 with a negative exponent returns float("inf"). It must not raise an exception.
  • base == 0.0 with a positive exponent returns 0.0.
  • Bases of 1.0 and -1.0 must work for any exponent. The sign for -1.0 depends on whether the exponent is odd or even.
  • The exponent can be as small as -2^31. Make sure your handling of negative exponents does not break on that value.
  • Results are compared with a relative tolerance of 1e-10.

Constraints

  • base is a floating-point number (it may be given as an integer).
  • -2^31 <= exponent <= 2^31 - 1
  • If the true result is too large or too small for a double, it is acceptable for the result to become inf or 0.0.
  • Time: O(log |exponent|). Extra space: O(1).

Examples

Example 1

Input: power_by_squaring(2, 10)

Output: 1024

Example 2

Input: power_by_squaring(2, -2)

Output: 0.25

Example 3

Input: power_by_squaring(-2, 3)

Output: -8

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

Loop over the bits of the exponent. Keep a running value equal to base^(2^i) that you square on every step, and multiply it into the answer whenever the current bit is 1.

Hint 3

For a negative exponent, invert the base once and then use the absolute value of the exponent. Handle a zero base and a zero exponent before inverting, since dividing by zero would fail.