Compute a^b mod m quickly using efficient binary exponentiation for applications. Supports huge numbers with automatic GMP, BCMath, or native algorithm seamlessly. Visualize intermediate squares and multiplies, then export tables and PDFs for sharing. Learn formulas, usage tips, and common pitfalls, fast today.
| # | Base (a) | Exponent (b) | Modulus (m) | a^b mod m |
|---|---|---|---|---|
| 1 | 5 | 117 | 19 | 1 |
| 2 | 4 | 13 | 497 | 445 |
| 3 | 7 | 560 | 561 | 1 |
| 4 | 2 | 1000 | 1009 | 942 |
| 5 | 123456789 | 12345 | 97 | 42 |
| # | Bit | Operation | Base | Result |
|---|
Goal: compute a^b mod m efficiently.
Binary (fast) exponentiation writes b in base two: b = \sum\_i 2^i. Repeatedly square and, when a bit is set, multiply the current result by the current base, always reducing modulo m. Complexity is O(log b) multiplications with modulus reductions.
// Pseudocode
res ← 1
x ← a mod m
while b > 0:
if b is odd: res ← (res · x) mod m
x ← (x · x) mod m
b ← floor(b / 2)
a, Exponent b, and Modulus m.This worked example shows binary exponentiation on a=5, b=117, m=19.
x = a mod m = 5 mod 19 = 5.117 = 11101012.1.| Loop | Bit | Operation | Base (x) | Result |
|---|---|---|---|---|
| 1 | 1 | multiply then square | 5 | 5 |
| 2 | 0 | square | 6 | 5 |
| 3 | 1 | multiply then square | 17 | 9 |
| 4 | 0 | square | 4 | 9 |
| 5 | 1 | multiply then square | 16 | 11 |
| 6 | 1 | multiply then square | 9 | 4 |
| 7 | 1 | multiply then square | 5 | 1 |
Therefore, 5117 mod 19 = 1. You can load this example from the table and compare steps.
| Domain | Why it matters |
|---|---|
| RSA | Exponentiation under large moduli enables encryption and signatures. |
| DH/EC | Powers modulo m underpin shared secret derivation. |
| Blockchain | Residues and proofs rely on modular operations. |
Binary exponentiation uses O(log b) squarings and at most that many multiplies.
| Exponent b | Bits | Iterations ≈ |
|---|---|---|
| 1,000 | ≈10 | 10 |
| 1,000,000 | ≈20 | 20 |
| 240 | 40 | 40 |
| 22048 | 2048 | 2048 |
Tip: Using GMP accelerates large integer arithmetic; BCMath provides precise string math.
| Input | Condition | Behavior |
|---|---|---|
| m = 0 | Invalid modulus | Error: modulus must be non‑zero. |
| b < 0 | Negative exponent | Error: negative exponent unsupported. |
| a < 0 | Negative base | Handled: reduced modulo m to [0, m). |
| a ≡ 0 (mod m) | Base multiple of m | Result is 0 unless b = 0. |
| b = 0 | Zero exponent | Result is 1 for any m ≠ 0. |
These cases are checked or handled in the calculator’s implementation.
Important Note: All the Calculators listed in this site are for educational purpose only and we do not guarentee the accuracy of results. Please do consult with other sources as well.