Skip to content
BytePatterns

Power Under A Modulus

MediumMath & Number Theory#fast-exponentiation#modular-arithmetic~25m

Problem

Compute base raised to exp, reported modulo mod, where the exponent can reach a billion. Building the power first and reducing afterwards would produce a number with hundreds of millions of digits, so the reduction has to happen along the way.

Examples

Input:  base = 2, exp = 10, mod = 1000
Output: 24
Why:    1024 % 1000
Input:  base = 7, exp = 1000000, mod = 13
Output: 9
Input:  base = 5, exp = 3, mod = 1
Output: 0
Why:    edge case, everything is congruent to 0 modulo 1

Hints

0 / 3

Stuck on the idea rather than the code? Fast Exponentiation covers it.