Module 4 : Modular Arithmetic

Lecture 2 : Modular exponentiation

A frequently occurring operation in number-theoretic computations is raising one number to a power modulo another number, also known as modular exponentiation . More precisely, we would like an efficient way to compute a b mod n , where a and b are nonnegative integers and n is a positive integer. They all are β bit numbers.
To compute ab (mod n ) we can adopt the following approach:

Perform b multiplications ( a × a × a × … × a ) mod n .

There are some drawbacks of this approach that are as follows:

  1. 1.  The intermediate result is too large to fit in memory.
  2. 2.  Not polynomial-time with respect to input size, since we are performing b multiplications where our input size is β ≅⌈ log b ⌉ .

Here we present a polynomial time algorithm to perform modular exponentiation using repeated squaring.

MODULAR-EXPONENTIATION ( a , b , n )

1 c ← 0
2 d ← 1
3 let < bkbk-1 ... b0 > be the binary representation of b .
4 for i = k down to 0
5         do c ← 2 c
6               d ← ( d · d ) mod n
7               if bi = 1
8                     then c c + 1
9                              d ← ( d · a ) mod n
10 return d


Here we note that the above program will run perfectly even if we remove the variable c altogether from the program. The variable c is retained to describe the loop invariant with which we establish the correctness of the above algorithm.