Problem 78
Modular Exponentiation
Medium · 20 pts · Math, Recursion
Problem
You are given integers A, B and M. Compute A^B mod M, the remainder when A raised to the power B is divided by M. By convention A^0 = 1, so for B = 0 the answer is 1 mod M (which is 0 when M = 1). B can be as large as 10^18, so multiplying A by itself B times is far too slow. Use fast exponentiation (exponentiation by squaring): look at the bits of B, square the base at each step, and multiply it into the result when the bit is 1, taking everything mod M. Products can reach 10^18, so use 64-bit arithmetic.
Input
Three integers A, B and M separated by spaces.
Output
Print A^B mod M.
Constraints
0 <= A <= 1000000000; 0 <= B <= 10^18; 1 <= M <= 1000000000
Example input
2 10 1000
Example output
24
Explanation
2^10 = 1024, and the remainder of 1024 divided by 1000 is 24. So the answer is 24.