← Interval & Math

Micro-Drill #120 — Fast power (iterative)

Interval & Math Target: 15s

Iterative binary exponentiation handles negative exponents. Same as pow(x, n).

def power(x, n):
    res = 1
    if n < 0: x, n = 1/x, -n
    while n:
        if n & 1: res *= x
        x *= x
        n >>= 1
    return res

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #119 Micro #121 →