Integer Power via Repeated Squaring
Math & Bit ManipulationAuto-graded · 25 test casesLast 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 == 0returns1.0for every base, including0.0.- A positive
exponentmeans the usual repeated multiplication. - A negative
exponentmeans the reciprocal:base ** exponent == 1 / (base ** -exponent). base == 0.0with a negativeexponentreturnsfloat("inf"). It must not raise an exception.base == 0.0with a positiveexponentreturns0.0.- Bases of
1.0and-1.0must work for any exponent. The sign for-1.0depends 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
baseis 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
infor0.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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Write the absolute value of the exponent in binary. For instance, x^13 = x^8 * x^4 * x^1 since 13 = 1101 in binary. Walk through the bits from least significant to most significant while maintaining two values:
x, which at stepiequalsbase^(2^i). It is squared on every iteration.result, the product accumulated so far. It is multiplied byxwhenever the current bit is 1.
For a negative exponent, use base^n = (1/base)^|n|. Invert the base once at the start, then run the same loop on |n|.
Special cases are handled before the loop:
- An exponent of
0returns1.0. - A zero base returns
0.0for a positive exponent andinffor a negative one. This avoids a division by zero.
Why it is correct
The loop keeps this invariant: result * x^m equals the target value, where m is the part of the exponent not yet processed.
- If
mis odd, multiplying one factor ofxintoresultand dropping the lowest bit keeps the invariant true. - Squaring
xwhile halvingmalso keeps it true.
When m reaches 0, result is the answer.
Inverting the base first, rather than taking 1 / base^|n| at the end, avoids an intermediate underflow to 0.0 that would then cause a division by zero. Python integers are unbounded, so negating -2^31 is safe. In a fixed-width language you would widen the exponent before negating.
Complexity
- Time: O(log |exponent|), at most 32 iterations.
- Space: O(1), since only a few scalars are used.
Reference solution
def power_by_squaring(base, exponent):
if exponent == 0:
return 1.0
if base == 0:
return float("inf") if exponent < 0 else 0.0
x = float(base)
n = exponent
if n < 0:
x = 1.0 / x
n = -n
result = 1.0
while n:
if n & 1:
result *= x
x *= x
n >>= 1
return result