Pow(x, n)

MediumFast exponentiationLeetCode 50 ↗World 8-11
0:00 / 0:00

Raise x to the power n in about log n steps: square the base and halve the exponent, setting aside one copy whenever it's odd.

▼

The problem

LeetCode 50 (Medium). Given a number x and an integer n (which can be negative, and as large as 2³¹ − 1 in magnitude), compute x to the power n.

Example: 2 to the 10th = 1024; 2 to the −2 = 1/4 = 0.25.

TRY IT ON LEETCODE ▶

The solution

def my_pow(x, n):
    if n < 0:
        x, n = 1 / x, -n
    result = 1
    while n:
        if n & 1:          # odd
            result *= x    # into the pouch
        x *= x             # square the base
        n >>= 1            # halve the exponent
    return result

Transcript

Pow x n. Given a number x and a whole number n, compute x to the power n. And n can be huge, or negative.

Take two to the tenth: ten twos multiplied, one thousand twenty-four. A negative power flips it: two to the minus two is one over four, a quarter.

The simple way multiplies x in, n times: ten blows of the hammer for two to the tenth. But n can be about two billion, so that's far too slow.

Here's the trick: squaring doubles the power. Square two for four, two to the second. Square again for sixteen, the fourth, then two fifty-six, the eighth. Three blows, not eight. So each step, square the base and halve the exponent. An odd exponent can't split evenly: one copy is left over, so drop it into the result first.

Let's forge two to the tenth. The result starts at one. Ten is even: square x to four, and halve n to five. Five is odd, so the pouch takes a four. Square x to sixteen; n drops to two, rounding down. Two is even: x becomes two fifty-six, and n is one. One is odd, so the pouch takes two fifty-six. Four times two fifty-six is one thousand twenty-four, in four steps, not ten.

Why those steps? Ten in binary is one zero one zero. Each step reads one bit, from the right, and the ones are the steps that filled the pouch.

In code: if n is negative, flip x to one over x and make n positive. Start the result at one. While n isn't zero: if n is odd, multiply the result by x. Then square x and halve n.

The exponent halves every step, so the time is log n: for two billion, just thirty-one steps. We only keep x, n and the result, so the space is constant.

Square the base, halve the power, pocket the odd ones. That's Pow x n.