Numbers and bits · 13 / 15 Exercise Hard

Modular exponentiation

Objective

Computing base**exp % mod with huge numbers is infeasible if you multiply exp times. Fast exponentiation walks the bits of the exponent: it squares the base at each step and multiplies the result when the bit is 1, always working modulo mod.

Instructions

  • The first line has the number n of cases. Each case is a line with base, exp and mod.
  • Show base**exp % mod for each case, without using pow with three arguments or the ** operator on the full power.
Input
3
2 10 1000
3 200 13
7 0 5
Output
24
9
1

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise