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:
- write the exponent b in binary, so b is a sum of powers of 2;
- square repeatedly to get a, a², a⁴, a⁸, …, reducing modulo m each time;
- multiply together the squares that match the 1 bits of b, again reducing after every product.
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
- Elementary Number Theory (Clark), Chapter 26: Computation of aᴺ mod m (binary method, 2⁶⁴⁴ mod 645 = 1) — LibreTexts Mathematics
- Elementary Number Theory (Raji), §3.5 Theorems of Fermat, Euler and Wilson — LibreTexts Mathematics
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