The purpose of modular exponentiation is to compute the
value
c
in equations of the form
c≡be(modn)
when
b,
e
and
m
are known (large) values. One of the algorithms to compute the value of
c
is exponentiation by squaring, also called binary
exponentiation or the right-to-left binary method. For
this fast algorithm it is required to convert the exponent
e
to binary notation. Below is an example implementation in Python,
followed by an example.
def modular_pow(base, exponent, modulus):
if modulus == 1:
return 0
result = 1
base = base % modulus
while exponent > 0:
if exponent % 2 == 1:
result = (result * base) % modulus
exponent = exponent >> 1
base = pow(base, 2, modulus)
return result
Example
As an example we compute:
524mod72
In order to compute this we first determine the binary representation
of the exponent:
24=110002
Note that
110002
has a length of 5, this means we only need 5 steps to compute the
exponentiation. We start with the following initial values:
exponentresultbase=110002=1=5
Because the exponent is even, we only perform the square. We then
shift the exponent one bit to the right:
exponentresultbase=110002≫1=11002=1=base2modn=52mod72=25
The exponent is even, so we perform the square and shift the exponent
one bit to the right.
exponentresultbase=11002≫1=1102=1=base2modn=252mod72=625mod72=49
Again the exponent is even, so we perform the square and shift the
exponent one bit to the right.
exponentresultbase=1102≫1=112=1=base2modn=492mod72=2401mod72=25
Now the exponent is odd. In this case we first perform the
multiplication of the result. We then square the base again and shift
the exponent one bit to the right.
exponentresultbase=112≫1=12=(result⋅base)modn=(1⋅25)mod72=25=base2modn=252mod72=625mod72=49
The last bit of the exponent is always odd. We perform both the
multiplication and the square and return the result.
exponentresultbase=12≫1=02=(result⋅base)modn=(25⋅49)mod72=1225mod72=1=base2modn=492mod72=2401mod72=25
We can now conclude that:
524mod72=1