Modular Exponentiation Calculator

Compute aᵇ mod m exactly for huge numbers with fast square-and-multiply, showing the binary exponent, the repeated squares and each multiplication.

Whole numbers with up to 100 digits in every box. A negative base is reduced modulo m first.
0 or more.
1 or more.

Results

aᵇ mod m
1
Exponent in binary
1010000100 (10 bits, 3 of them 1)
Multiplications needed
11 (9 squarings + 2 multiplications), instead of 643 one at a time
Square-and-multiply steps
Exponent in binary: 644 = 1010000100₂ = 2⁹ + 2⁷ + 2² Successive squares mod 645: 2¹ ≡ 2 2² ≡ 2² = 4 ≡ 4 2⁴ ≡ 4² = 16 ≡ 16 2⁸ ≡ 16² = 256 ≡ 256 2¹⁶ ≡ 256² = 65536 ≡ 391 2³² ≡ 391² = 152881 ≡ 16 2⁶⁴ ≡ 16² = 256 ≡ 256 2¹²⁸ ≡ 256² = 65536 ≡ 391 2²⁵⁶ ≡ 391² = 152881 ≡ 16 2⁵¹² ≡ 16² = 256 ≡ 256 Multiply the squares for the 1 bits: 2⁶⁴⁴ = 2⁵¹² × 2¹²⁸ × 2⁴ 256 × 391 = 100096 ≡ 121 121 × 16 = 1936 ≡ 1

How it’s calculated

Computing aᵇ mod m directly is hopeless for big numbers: 2⁶⁴⁴ alone has 194 digits. Square-and-multiply (also called successive or repeated squaring) keeps every number below m² by reducing after each step:

b = 2ᵏ¹ + 2ᵏ² + … ⇒ aᵇ = a^(2ᵏ¹) × a^(2ᵏ²) × … a^(2ᵏ⁺¹) = (a^(2ᵏ))² (mod m) about log₂ b squarings plus one multiplication per extra 1 bit

Example: 2⁶⁴⁴ mod 645. 644 = 1010000100₂ = 2⁹ + 2⁷ + 2². Squaring modulo 645 gives 2² ≡ 4, 2⁴ ≡ 16, 2⁸ ≡ 256, 2¹⁶ ≡ 391, 2³² ≡ 16, 2⁶⁴ ≡ 256, 2¹²⁸ ≡ 391, 2²⁵⁶ ≡ 16 and 2⁵¹² ≡ 256. Then 2⁶⁴⁴ = 2⁵¹² × 2¹²⁸ × 2⁴ ≡ 256 × 391 × 16. 256 × 391 = 100,096 ≡ 121 and 121 × 16 = 1,936 ≡ 1 (mod 645): 9 squarings and 2 multiplications instead of 643 multiplications.

Frequently asked questions

Why reduce after every step?

Because (x × y) mod m = ((x mod m) × (y mod m)) mod m. Reducing keeps every intermediate number smaller than m², so even a 100-digit exponent needs only a few hundred small multiplications.

Where is modular exponentiation used?

In RSA and Diffie–Hellman cryptography, in primality tests such as the Fermat and Miller–Rabin tests, and for questions like “what is the last digit of 7¹⁰⁰⁰?” (that is 7¹⁰⁰⁰ mod 10 = 1).

What does 2⁶⁴⁴ ≡ 1 (mod 645) tell me?

Fermat’s little theorem says aᵖ⁻¹ ≡ 1 (mod p) when p is prime. 645 = 3 × 5 × 43 is not prime, yet it passes this test for base 2, so it is a pseudoprime to base 2.

Can the exponent be negative?

Not directly. a⁻ᵇ mod m means (a⁻¹)ᵇ mod m, so first find the modular inverse of a (it exists when gcd(a, m) = 1) and raise that to the power b.

Embed this calculator

Add this free calculator to your own website. Copy the code below into your page’s HTML:

Need this calculator branded, changed or built around your own prices?See custom business solutions →

Sources

Formulas are taken from the free public references above. Results are provided “as is” for informational and educational purposes only. See our disclaimer.

Added · Last updated · How we check our calculators

Spotted a mistake or missing option? Report a problem· Suggest a calculator