Skip to content
StackDecode
Number theory & mathAnimated

Binary Exponentiation

Use the binary digits of the exponent to multiply selectively.

Time

O(log n)

Extra space

O(1)

Use it for

Powers and matrix powers.

How it works

  1. Binary exponentiation reads the exponent’s binary digits from the lowest bit.
  2. result starts at 1. If the bit is 1, multiply result by the current base.
  3. Square the base and shift the exponent right for the next bit. O(log e) multiplications.

Watch it run

Loading animation…