Implement Binary Exponentiation
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Evaluate floating-point powers with integer exponents using logarithmic time binary exponentiation without standard library power methods.
Write a function my_pow(base: float, exponent: int) -> float that computes the value of base raised to the power of exponent ($base^{exponent}$).
You must not use built-in exponential operators or standard math exponentiation functions (such as Python's ** operator or pow()/math.pow()).
Rules & Edge Cases
- An exponent of
0should return1.0. - For negative exponents, use the mathematical identity $x^{-n} = \left(\frac{1}{x}\right)^n$.
- The algorithm should execute in $O(\log |exponent|)$ time complexity.
Constraints
-100.0 < base < 100.0-2^31 <= exponent <= 2^31 - 1exponentis a 32-bit signed integer.
Examples
Example 1
Input: my_pow(2, 10)
Output: 1024
Example 2
Input: my_pow(2.1, 3)
Output: 9.261000000000001
Example 3
Input: my_pow(2, -2)
Output: 0.25
Hints
Hint 1
Recall that any exponent can be decomposed into powers of 2 using its binary representation.
Hint 2
Consider how base^(2^k) can be computed repeatedly by squaring the previous term.
Hint 3
For negative exponents, convert the base to its reciprocal (1 / base) and make the exponent positive.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A naive linear multiplication approach performs $|exponent|$ multiplications, which is too slow for 32-bit integer limits (up to $\approx 2 \times 10^9$ operations).
Instead, we can use exponentiation by squaring (binary exponentiation). Any positive integer exponent $n$ can be represented in binary: $$n = b_k 2^k + b_{k-1} 2^{k-1} + \dots + b_0 2^0$$ This means $x^n$ can be rewritten as a product of terms $x^{2^i}$ for all bit positions $i$ where $b_i = 1$.
- Handling Negative Exponents:
If
exponent < 0, invertbaseto1.0 / baseand flip the sign ofexponentto make it positive. - Iterative Binary Exponentiation:
- Maintain a running accumulator
result = 1.0and a current factor initialized tobase. - While
exponent > 0:- If the lowest bit of
exponentis set (exponent & 1), multiplyresultbybase. - Square the
base(base *= base) to represent the power of 2 for the next bit position. - Right shift
exponentby 1 bit (exponent >>= 1).
- If the lowest bit of
- Maintain a running accumulator
Complexity Analysis
- Time Complexity: $\mathcal{O}(\log |exponent|)$. The binary representation of a 32-bit integer has at most 32 bits, meaning the loop runs at most 32 times.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space since state is maintained across a few scalar variables.
Python Source Code
def my_pow(base: float, exponent: int) -> float:
if exponent < 0:
base = 1.0 / base
exponent = -exponent
result = 1.0
while exponent > 0:
if exponent & 1:
result *= base
base *= base
exponent >>= 1
return result