I have been studying this link from wikipedia of modulo of a large number, Here is the pseudocode.
function modular_pow(base, exponent, modulus)
result := 1
while exponent > 0
if (exponent mod 2 == 1):
result := (result * base) mod modulus
exponent := exponent >> 1
base = (base * base) mod modulus
return result
I don't understand the explanation given in wiki.Why I have to check if exp%2 is even or odd. also why I am doing the three operations?
This algorithm is a combination of the Exponentiation by Squaring algorithm and modulo arithmetic.
To understand what's going on, first consider a situation when
exponent
is a power of2
. Then, assuming thatexponent = 2 ^ k
, the result could be computed by squaring the resultk
times, i.e.When
exponent
is not a power of2
, we need to make additional multiplications. It turns out that if we can divideexponent
by 2 without remainder, we can square the base, and divide the exponent. If, however, there is a remainder, we must additionally multiply the intermediate result by the value of the currentbase
.What you see is the same exponentiation by squaring applied to modulo multiplication. The algorithm denotes integer division by two using the
exponent >> 1
operation, which is identical tofloor(exponent / 2)
.