Skip to main content

Exponentiation

Now we may ask ourselves: How fast can we do these modular arithmetic operations? When we multiply two nn-digit numbers, it is easy to see that a school multiplication method would give us O(n2)O(n^2) bit operations. But what about exponentiation? In particular, how fast can we compute ab(modm)a^b \pmod{m}? If we do multiplications aaaa \cdot a \ldots \cdot a (bb times), this would require O(bn2)O(b n^2) bit operations which is inefficient (recall that the encoding length of bb is only O(logb)O(\log b), so this running time is exponential in the size of the input). We can do much better with the method of repeated squaring.

ModExp(a,b,m)\mathrm{Mod-Exp}(a,b,m)

  1. X1X \leftarrow 1, BbB\leftarrow b, Aa(modm)A \leftarrow a \pmod{m}
  2. while B1B \geq 1 do
    1. if BB is odd, then BB1B \leftarrow B-1, XAX(modm)X\leftarrow A X \pmod{m}
    2. else BB/2B \leftarrow B/2, AA2(modm)A\leftarrow A^2 \pmod{m}
  3. return XX
Exercise 45

Prove that the following is loop invariant:

XAB=ab(modm)X A^B = a^b \pmod{m}

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 B=0B=0. Therefore, X=ab(modm)X = a^b \pmod{m} and the returned value is correct. The running time analysis follows from the following exercise:

Exercise 46

After every two rounds, the value of BB is reduced to less than half.

This implies that if BB originally has nn bits, the number of rounds would be at most 2n2n. Each round only involves basic multiplications (with complexity O(n2)O(n^2)). Therefore, the total running time of this algorithm is O(n3)O(n^3).1

Footnotes

  1. Note that, to simplify the analysis, in this section we assumed that the number of bits of aa, bb and mm is nn.