~/problems / Number theory / Modular arithmetic

Power with a huge digit-list exponent

medium ~20 min

Write super_pow(a: int, b: list[int]) -> int that returns a^B mod 1337, where the exponent B is given as its list of decimal digits b, most significant first. B can have thousands of digits.

Don't turn b into one giant integer, and don't call Python's three-argument pow: the tests can't stop you, but writing your own small modular power helper is the skill being drilled. Aim for O(len(b)) modular powers with small exponents.

super_pow(2, [3])        # 8
super_pow(2, [1, 0])     # 1024 % 1337 = 1024
super_pow(3, [1, 0, 0])  # 3^100 % 1337
super_pow(1337, [5])     # 0

Constraints: 1 ≤ a ≤ 2^31 - 1, 1 ≤ len(b) ≤ 2000, b has no leading zeros (unless it is [0], meaning a^0 = 1).

Show hint

Walk the digits left to right. If X is the exponent read so far and d the next digit, then a^(10·X + d) = (a^X)^10 · a^d, so the running result only ever needs small powers, all taken mod 1337.

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc