Modular exponentiation Created 2026-10-06 Updated 2026-10-14
Modular exponentiation computes the remainder for an integer base , a nonnegative integer exponent , and, here, an integer modulus . It applies exponentiation by squaring while reducing after each multiplication, including each squaring. The result is the unique representative in . There is no requirement that the base be coprime to the modulus when the exponent is nonnegative.[ref]
A Computational Introduction to Number Theory and Algebra by Victor Shoup. Section 3.4, pp. 64–66: canonical representatives, modular products, and nonnegative-exponent repeated squaring
Take , , and . Initialize ; the remaining digits giveHence . The final operation multiplies by , since the preceding square has already been reduced. The computation never needs to construct .
In general reduce the base first, . For , initialize and process the remaining binary digits with , followed, for a digit one, by . The loop invariant iswhere is the processed prefix value. The congruence is preserved because modular arithmetic respects multiplication: if , then and . Thus changing representatives never changes the final congruence class.
Both factors in every product are less than , so the unreduced product is less than , and the stored result is again less than . The same bounds hold for a gigantic exponent, such as : there are squarings, each on bounded-size residues. For base two, the corresponding ordinary power would have binary digits. The benefit is avoiding the huge ordinary power altogether, rather than constructing it and taking one final remainder. Initial reduction is essential when the supplied base is much larger than the modulus.
For , return under the same empty-product convention as exponentiation by squaring. For , require , find the modular multiplicative inverse , and compute ; the extended Euclidean algorithm can find that inverse. Its cost is separate from the positive-exponent binary powering multiplication count. For example, , while is undefined because and are not coprime.
A reversible computation gives the coherent quantum modular exponentiation used in quantum order finding and discrete-logarithm Fourier sampling.