 # repeated squaring

(algorithm)

Definition: Compute the nth 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 x13 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 = 1101 `
Start 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
x1 1
Least significant bit of exponent is 1, so multiply a = a * s
x1 x1
Square s
x1
Next bit is 0, so don't multiply
x1
Square s
x4 x1
Next bit is 1, so multiply
x4 x5
Square s
x8 x5
Highest bit is 1, so multiply
x8 x13

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

`     x13 = x1101			 						         = x(1*2^3 + 1*2^2 + 0*2^1 + 1*2^0)		 						         = x1*2^3* x1*2^2* x0*2^1* x1*2^0		 						         = x2^3  * x2^2  *  1    * x2^0  						         = x8    * x4            * x1  `
The values to be multiplied are successive squares (variable s above). By multiplying appropriate powers, we can compute an integral power in logarithmic time.

There are many variations. For instance, to find an 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