Algorithm Implementation/Mathematics/Modular Exponentiation

Algorithm
Here we show the modular exponentiation algorithm for integers - a way to efficiently compute $a^{e} (mod n)$. This general algorithm may also be used for other algebraic structures which have multiplication and exponentiation and is efficient when the size of values has an upper bound - the modulus. Other structures which can use this basic algorithm include matrix exponentiation with floating point coefficients and elliptic curve computations over finite fields (although in that case the operation is called multiplication, not exponentiation).

Low to High Algorithm
This is the most intuitive algorithm. The algorithm scans the exponent, a bit at a time, and if the $n$th bit has the value 1, multiplies the accumulator by $a^{2^n}$, which is computed by successive squaring as the exponent is traversed.

A pseudocode description is: function powmod(a, e, n)    accum := 1 x = e   // Scan the bits of the exponents apow := a // Successive powers, a^(2^n) while (x ≠ 0) if (x is odd) accum := accum &times; apow (mod n)         Divide x by 2 apow : = apow^2 (mod n)    return accum

High to Low Algorithm
This algorithm uses slightly less memory - not requiring separate storage of the powers of $a$, and is also more efficient if the base $a$ has a special structure (such as being small), making multiplication by it easy. The algorithm scans the exponent, a bit at a time, from the bit immediately following the top bit to the low order bit.

A pseudocode description is: function powmod(a, e, n)    accum := a     if (e = 0) return 1  // A special case for (bitptr := highbit(e) - 1;  bitptr >= 0;  bitptr--) accum := accum^2 (mod n)         if (e[bitptr] = 1) accum := accum &times; a (mod n)    return accum

Low-to-High algorithm with GMP
GMP allows for calculating with arbitrary precision. The GMP library has a  function, so this is not needed, but is here strictly for expository value.

Low-to-High algorithm with BigInteger
The Java BigInteger class has a  method, so this is not needed, but is here strictly for expository value.

Low-to-High algorithm
Python has a  function, so this is not needed, but is here strictly for expository value.