Given two integers A and X, think about how to compute AX. The value can be enormous, so compute it modulo 109+7. Writing amodx for the remainder of a divided by x,
(a×b)modx={(amodx)×(bmodx)}modx
holds. The remainders of two integers modulo 1,000,000,007 are therefore enough to compute the remainder of their product.
So multiplying A by itself X times looks like it would work. When X grows into the range of a 64 bit integer, multiplying one factor at a time takes far too long to finish. Reduce the number of multiplications like this.
- Compute A1,A2,A4,A8,… in order. Each number is the square of the previous one, and stopping as soon as the exponent would pass X is enough. Since X stays inside a 64 bit integer, fewer than 64 numbers are computed.
- Now write X in binary. For X=11, 11=1+2+8, and by the law of exponents A11=A1+2+8=A1×A2×A8. Multiplying a few of the numbers from step 1 gives AX.
Multiplying one factor at a time costs time proportional to X, while the method above costs time proportional to logX. Write a program that computes AX modulo 109+7.