~/problems / Number theory / Modular arithmetic

Modular exponentiation

easy ~15 min

Write power_mod(a: int, b: int) -> int that returns a^b mod 1_000_000_007. By convention 0^0 = 1.

Compute the power yourself: don't use Python's three-argument pow (the tests can't stop you, but that skips the drill). A loop of b multiplications is hopeless for b near 10^9; aim for O(log b) multiplications, reducing mod 10^9 + 7 after each one.

power_mod(3, 4)      # 81
power_mod(2, 10)     # 1024
power_mod(0, 0)      # 1
power_mod(123, 0)    # 1
power_mod(2, 40)     # 511620083

Constraints: 0 ≤ a, b ≤ 10^9. The tests call it tens of thousands of times.

Show hint

Look at the bits of b: keep a running result and a base that you square at every step, and multiply the base into the result only when the current bit is set.

Topic: Modular arithmetic. Fast exponentiation, Fermat inverses, nCr mod p with factorial tables.

0:00
Ctrl ' run · Ctrl ↵ submit
esc