Pow(x, n) in Python


Suppose we have two inputs x and n. x is a number in range -100.0 to 100.0, and n is a 32-bit signed integer. We have to find x to the power n without using library functions.

So if the given inputs are x = 12.1, n = -2, then output will be 0.00683

To solve this, we will follow these steps −

  • power := |n| and res := 1.0
  • while power is not 0
    • if last bit of power is 1, then res := res * x
    • x := x * x
  • if n < 0
    • return 1 / res
  • return res

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def myPow(self, x, n):
      power = abs(n)
      res = 1.0
      while power:
         if power & 1:
            res*=x
         x*=x
         power>>=1
      if n<0:
         return 1/res
      return res
ob1 = Solution()
print(ob1.myPow(45, -2))
print(ob1.myPow(21, 3))

Input

45
-2
21
3

Output

0.0004938271604938272
9261.0

Updated on: 27-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements