Exponentiation by squaring
ID: exponentiation-by-squaring
Exponentiation by squaring computes an integer power by reading the exponent's binary expansion. Appending a binary digit to a prefix of value replaces by , so the corresponding power changes byEach new digit requires one squaring and, only for digit one, one further multiplication. The number of digits grows with the logarithm of the exponent, making this useful for modular exponentiation, primality testing, and powers of matrices using matrix multiplication.[ref]
A Computational Introduction to Number Theory and Algebra by Victor Shoup. Section 3.4, pp. 65–66: binary-prefix recurrence and repeated-squaring algorithm; p. 67: primality-testing application
For a concrete calculation, , so . The optimized left-to-right algorithm used here instead keeps one accumulated power: initialize from the leading digit one, then process only the remaining digits :Thus , using three squarings and two further multiplications, instead of twelve successive multiplications starting at .
For a general positive integer with leading digit , set and, for , first replace by , then multiply it by if . Return . This explicitly skips the leading digit's otherwise unnecessary operations on one. A Computational Introduction to Number Theory and Algebra by Victor Shoup (Section 3.4, pp. 65–66) presents the version initialized at one and processing every digit; the optimization here makes the counting convention unambiguous.
The loop invariant is , where is the value of the digits already read. Initially and . If the next digit is , then squaring and optionally multiplying give , exactly the next prefix. At termination . This proof uses associativity of multiplication; it works in any monoid, including matrices with the identity matrix as identity element, and needs no commutativity between different bases.
For , return the identity element without performing a multiplication. This is the empty-product convention ; if , the algorithm therefore returns one for by convention, rather than resolving its meaning in every mathematical setting. Negative integer exponents require an inverse element: compute , counting the inversion separately. Over the integers, such an inverse generally leaves the integers, and a zero base has no inverse.
Exponentiation by squaring is an efficient algorithm used to compute powers of a number, particularly useful for large exponents. This method reduces the number of multiplications needed, making it much faster than the naive approach of multiplying the base by itself repeatedly. The basic idea behind exponentiation by squaring is to take advantage of the properties of exponents.
New to topics? Read the docs here!
