Advertisement
bennyfromtheblock

50. Pow(x, n)

Oct 17th, 2021
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. # Divide and conquer approach
  2. # intuition: x^(2n) = (x^n)^2
  3. # i.e. x^(N) = (x^(N/2))^2 if N is even
  4. # if the exponent is odd, lets say N = 2M+1, then x^(N) = (x^M)^2 * x
  5.  
  6. # TC: log(n)
  7. # SC: log(n) from recursion stacks
  8.  
  9. class Solution:
  10.     def myPow(self, x: float, n: int) -> float:
  11.        
  12.         def fastPow(x: float, n: int) -> float:
  13.             if n == 0:
  14.                 return 1.0
  15.            
  16.             half = fastPow(x, n // 2) # floor divide will leave 1 out if n is odd
  17.             if n % 2 == 0:
  18.                 return half * half
  19.            
  20.             return half * half * x # if n is odd, multiply by x again
  21.        
  22.         if n < 0:
  23.             x = 1 / x
  24.             n = -n
  25.            
  26.         return fastPow(x, n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement