Pow(x, n) in Python

Calculating x to the power n efficiently without using built-in functions like pow() or ** is a common programming problem. We can implement this using binary exponentiation, which reduces time complexity from O(n) to O(log n).

Problem Statement

Given two inputs x and n, where x is a number in range -100.0 to 100.0 and n is a 32-bit signed integer, we need to calculate xn efficiently.

Example

If x = 12.1 and n = -2, then xn = 12.1-2 = 1/(12.1)2 = 0.00683

Algorithm

We use binary exponentiation which works by breaking down the exponent into its binary representation ?

  • Initialize power = |n| and result = 1.0
  • While power is not 0:
    • If the last bit of power is 1, multiply result by x
    • Square x and right-shift power by 1 bit
  • If n is negative, return 1/result
  • Otherwise, return result

Implementation

class Solution:
    def myPow(self, x, n):
        power = abs(n)
        result = 1.0
        
        while power:
            if power & 1:  # Check if last bit is 1
                result *= x
            x *= x
            power >>= 1    # Right shift by 1 bit
        
        if n < 0:
            return 1 / result
        return result

# Test the implementation
solution = Solution()
print(f"45^(-2) = {solution.myPow(45, -2)}")
print(f"21^3 = {solution.myPow(21, 3)}")
print(f"2.1^2 = {solution.myPow(2.1, 2)}")
45^(-2) = 0.0004938271604938272
21^3 = 9261.0
2.1^2 = 4.41

How It Works

The algorithm uses the binary representation of the exponent. For example, to calculate x13 where 13 in binary is 1101 ?

  • 13 = 8 + 4 + 1 = 2³ + 2² + 2?
  • x13 = x8 × x4 × x1
  • We can compute x1, x2, x4, x8 by repeatedly squaring

Edge Cases

solution = Solution()

# Test edge cases
print(f"Any number^0 = {solution.myPow(5, 0)}")
print(f"0^positive = {solution.myPow(0, 5)}")
print(f"1^any = {solution.myPow(1, -100)}")
print(f"Negative base = {solution.myPow(-2, 3)}")
Any number^0 = 1.0
0^positive = 0.0
1^any = 1.0
Negative base = -8.0

Time and Space Complexity

Approach Time Complexity Space Complexity
Naive (multiply n times) O(n) O(1)
Binary Exponentiation O(log n) O(1)

Conclusion

Binary exponentiation efficiently calculates xn in O(log n) time by using the binary representation of the exponent. This approach handles both positive and negative exponents correctly.

Updated on: 2026-03-25T07:46:58+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements