Exponentiation by squaring
Exponentiation by squaring is a fast way to raise a base to an integer exponent by considering the binary digits of the exponent.
Algorithm
Begin with a partial product , initially empty (equal to ) and a factor , initially equal to the base.
Starting on the rightmost binary digit of the exponent and ending on the leftmost digit,
- If the exponent digit is , multiply by ; if the digit is , leave as is,
- Square ,
- Move left one digit.
The final value of is the result. When considering the leftmost digit, the step of squaring can be skipped, since no future multiplications of into will occur.
Efficiency
The speed gained by exponentiation by squaring over simply repeatedly multiplying the base by itself is analogous to the speed gained during multiplication by distributing and multiplying the digits of both factors rather than repeatedly adding one factor to itself. In other words, the concept of "square and multiply" is similar to "shift (multiply by ) and add", and offers similar improvement to efficiency.
Applications
For ordinary powers of integer bases, exponentiation by squaring is not immediately effective because the rapidly growing sizes of the partial product and the squared factor essentially cancel out the advantage of using fewer multiplications. However, it is tremendously helpful in exponentiation of an integer modulo another integer, in which the size of the partial products remains contained. Also, exponentiation by squaring can be effective when the base is a floating point number, whose length in significant figures remains the same after multiplication by another floating point number, although precision errors can accumulate if the exponent is large enough.
Example with modular exponentiation
Problem: Verify Fermat's Little Theorem for and .
Solution: We want to find . Doing eighteen multiplications would be tedious, but we can accomplish the calculation more quickly. We write .
The rightmost binary digit is , so we multiply a into the result (partial product). To advance the digit in consideration leftward, we square , obtaining .
Now the digit in consideration is again a , so we multiply the result (currently ) by to obtain . We square to prepare for the next digit, obtaining .
This time, the digit is a , so we square (producing ) and do not alter the result. Likewise, the next digit is a , so we square again to get . Now the digit in consideration (the leftmost digit) is , so we multiply the result by . There is no need to square after the final, leftmost digit; , so , as desired.
The following table provides a summary of the variable values throughout the calculation, where is the partial product and is the current factor after squaring.
The approach may be visualized as using the fact that and that exponents that are themselves powers of can all be easily managed using a single course of repeated squaring.