Compute a Power Using Fast Exponentiation

Implement computePower

Given an integer base x and a non-negative integer exponent n, compute x raised to the power n. Multiplying x by itself n times works, but it treats every exponent as fundamentally n separate units of work. Recursive squaring exploits a shortcut instead: x^n is just (x^(n/2))² when n is even (with one extra factor of x tacked on when n is odd) — so the exponent can be halved at every single recursive call rather than merely decremented. Reaching the base case (n=0, trivially 1) this way takes only O(log n) calls, turning what would be a million multiplications for a million-sized exponent into roughly twenty.

Example 1:

Input: x = 3, n = 12

Output: 531441

Example 2:

Input: x = 2, n = 20

Output: 1048576

Example 3:

Input: x = 10, n = 9

Output: 1000000000

+ 3 hidden test cases run on Submit.

Constraints:

  • -10 ≤ x ≤ 10, x ≠ 0
  • 0 ≤ n ≤ 20
  • The result always fits comfortably within a 32-bit signed integer for this input range

x =

3

n =

12