Problem 479501 · easy · Level 04 Non-Linear Data Structures

Power with Fast Exponentiation

recursion · divide and conquer · exponentiation by squaring

Multiplying x by itself n times takes n steps. There is a much faster idea: since x**8 == (x**4)**2, you can compute x**(n//2) once and square it. Each recursive call halves n, so only about log2(n) multiplications are needed.

Implement power(x, n) that returns x raised to the integer power n without using **, pow() or math.pow. n may be negative, in which case x**n == 1 / x**(-n). When x is an int and n >= 0, return an exact int, as x ** n does: a float cannot hold a number as large as 2 ** 10000.

Examples

Input:  x = 3, n = 9
Output: 19683
Input:  x = 2.0, n = -3
Output: 0.125
Input:  x = -2, n = 3
Output: -8

Constraints

  • x is an int or float, x != 0 when n < 0
  • -10**6 <= n <= 10**6
  • A solution that recurses once per unit of n will exceed the recursion limit on large n.

Goals

  • Halve the problem size at each recursive step instead of shrinking it by one
  • Handle even/odd cases and negative exponents in a recursion
  • Recognise O(log n) recursion depth versus O(n)
Starting Python…