(algorithm)

**Definition:**
Compute the n^{th} power of an expression in *Θ(log n)* steps by repeatedly squaring an intermediate result and multiplying an accumulating value by the intermediate result when appropriate.

*Note:
To find x ^{13} one could multiple 13 x's together. This is slow if multiplication is time consuming (e.g., matrix multiplication) or the exponent is very large. *

Instead, write the exponent in binary notation.

13 = 1101Start with a "squares" value (s) equal x and an "accumulated" value (a) equal 1. Reading from least significant bit to most significant, when there is a 1 in the binary notation, multiply a by s. Keep squaring s.

s | a | |
---|---|---|

x^{1} | 1 | |

Least significant bit of exponent is 1, so multiply a = a * s | ||

x^{1} | x^{1} | |

Square s | ||

x² | x^{1} | |

Next bit is 0, so don't multiply | ||

x² | x^{1} | |

Square s | ||

x^{4} | x^{1} | |

Next bit is 1, so multiply | ||

x^{4} | x^{5} | |

Square s | ||

x^{8} | x^{5} | |

Highest bit is 1, so multiply | ||

x^{8} | x^{13} |

Why does this work? Consider the exponent decomposed into binary notation.

xThe values to be multiplied are successive squares (variable s above). By multiplying appropriate powers, we can compute an integral power in logarithmic time.^{13}= x^{1101}

= x^{(1*2^3 + 1*2^2 + 0*2^1 + 1*2^0)}

= x^{1*2^3}* x^{1*2^2}* x^{0*2^1}* x^{1*2^0}

= x^{2^3}* x^{2^2}* 1 * x^{2^0}

= x^{8}* x^{4}* x^{1}

* There are many variations. For instance, to find a ^{n} mod m for very large n, reduce modulo m along the way. Fibonacci numbers can be computed quickly by repeated squaring of a suitable expression. If addition and doubling were much faster than multiplication, one could multiply by repeatedly doubling and summing.*

Author: PEB

How do you compute 1415^13 mod 2537 with a calculator? (PDF). To work out powers mod n, use repeated squaring.

Go to the Dictionary of Algorithms and Data Structures home page.

If you have suggestions, corrections, or comments, please get in touch with Paul Black.

Entry modified 12 June 2013.

HTML page formatted Wed Mar 13 12:42:46 2019.

Cite this as:

Paul E. Black, "repeated squaring", in
*Dictionary of Algorithms and Data Structures* [online], Paul E. Black, ed. 12 June 2013. (accessed TODAY)
Available from: https://www.nist.gov/dads/HTML/repeatedSquaring.html