Skip to content
StackDecode
Number theory & mathAnimated

Fast Exponentiation

Square the base and halve the exponent.

Time

O(log n)

Extra space

O(1)

Use it for

Large powers quickly.

How it works

  1. Computing b^e by multiplying e times is slow for large e.
  2. Write e in binary. Keep squaring the base; whenever the current bit of e is 1, multiply it into the result.
  3. Only about log₂ e squarings are needed.

Watch it run

Loading animation…