01
Implement fast exponentiation to compute x to the power n in O(log n).
Show answer
def power(x, n):
if n < 0:
x, n = 1 / x, -n
result = 1
while n > 0:
if n & 1: # odd bit set: multiply current base in
result *= x
x *= x # square the base
n >>= 1 # move to next bit
return result
# power(2, 10) == 1024; use % mod after each multiply for modular power