Binary Exponentiation — Square and Multiply

Compute an mod m in O(log n). Read the bits of n from the right: every step squares the base; when the current bit is 1 the base is multiplied into the result. Watch the invariant result · basen = aN hold throughout.

Exponent n in binary (read right → left, lowest bit first)

n = 13 = 1101₂ = 8 + 4 + 1  ⇒  a13 = a8 · a4 · a1
bit = 1 (multiply this rung in) bit = 0 (skip) current bit

Running registers

result  (starts at identity 1)
1
a0 = 1
base  (starts at a, squared each step)
3
a1
Press Step to process the lowest remaining bit, or Run to animate.
step 0 / 0
squarings 0
multiplies 0
remaining n 13

Complexity

ApproachMultiplicationsNote
Naive loopO(n)one multiply per unit of n
Binary exponentiationO(log n)square-and-multiply
  squarings⌊log₂ n⌋one per bit
  multipliespopcount(n)one per set bit
SpaceO(1)two registers

Operation log

Invariant maintained at the top of every step: result · base^(remaining n) = a^N. When remaining n reaches 0, result = a^N mod m. The same loop, with matrix multiply instead of scalar multiply, powers a matrix for fast Fibonacci (see 11-matrix-exponentiation).