11-3. Integer Exponentiation

Computing xn by Binary Decomposition of n

A well-known technique for computing xn, when n is a nonnegative integer, involves the binary representation of n. The technique applies to the evaluation of an expression of the form xxxx • … • x where • is any associative operation, such as addition, multiplication including matrix multiplication, and string concatenation (as suggested by the notation (‘ab’)3 = ‘ababab’). As an example, suppose we wish to compute y = x13. Because 13 expressed in binary is 1101 (that is, 13 = 8 + 4 + 1),

Thus, x13 may be computed as follows:

This requires five multiplications, ...

Get Hacker's Delight now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.