Skip to content
StackDecode
Number theory & mathAnimated

Modular Exponentiation

Compute b^e mod m by repeated squaring, reducing as you go.

Time

O(log e)

Extra space

O(1)

Use it for

RSA, primality tests.

How it works

  1. Numbers get huge in b^e, so reduce modulo m after every multiplication: (x · y) mod m = ((x mod m) · (y mod m)) mod m.
  2. Use the same square-and-multiply loop as fast exponentiation.
  3. All values stay below m, so it is fast and safe. This is the core of RSA and Diffie–Hellman.

Watch it run

Loading animation…