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
- Computing b^e by multiplying e times is slow for large e.
- Write e in binary. Keep squaring the base; whenever the current bit of e is 1, multiply it into the result.
- Only about log₂ e squarings are needed.
Watch it run
Loading animation…