Exponentiation
Now we may ask ourselves: How fast can we do these modular arithmetic operations? When we multiply two -digit numbers, it is easy to see that a school multiplication method would give us bit operations. But what about exponentiation? In particular, how fast can we compute ? If we do multiplications ( times), this would require bit operations which is inefficient (recall that the encoding length of is only , so this running time is exponential in the size of the input). We can do much better with the method of repeated squaring.
- , ,
- while do
- if is odd, then ,
- else ,
- return
Prove that the following is loop invariant:
From the above exercise and the fact that the initialized value satisfies the loop invariant's condition, we know that the condition must hold at the end of the algorithm, which has . Therefore, and the returned value is correct. The running time analysis follows from the following exercise:
After every two rounds, the value of is reduced to less than half.
This implies that if originally has bits, the number of rounds would be at most . Each round only involves basic multiplications (with complexity ). Therefore, the total running time of this algorithm is .1
Footnotes
-
Note that, to simplify the analysis, in this section we assumed that the number of bits of , and is . ↩