Modular exponentiation computes base^exp mod m — and this tool does it the
right way, with the fast square-and-multiply algorithm, so even thousand-digit
exponents resolve instantly. It is the workhorse behind RSA, Diffie-Hellman, and
primality tests.
Why you cannot just compute base^exp first
For a base of 7 and an exponent of 512, the naive result has roughly 433 decimal digits. For a 2048-bit RSA key, the exponents involved have hundreds of digits themselves — the raw power would have millions of digits. No computer can store or operate on a number that large directly.
The solution is to reduce modulo m at every step, keeping every intermediate
value small throughout the process.
How it works
The modulus is applied after every multiplication, using the square-and-multiply (binary exponentiation) method:
result = 1
b = base mod m
while exp > 0:
if exp is odd: result = (result × b) mod m
b = (b × b) mod m # square
exp = exp >> 1 # next bit
Because every intermediate value stays below m², and the loop runs only about
log2(exp) times, the answer is found extremely quickly regardless of how large
the exponent is. This tool uses JavaScript’s BigInt type, so there is no
practical limit on the size of the numbers you enter.
Worked examples
Small example: (7^256) mod 13
This requires only 8 squaring steps even though 7^256 itself has 217 decimal
digits. The answer is 9.
A number-theory check: (2^10) mod 7 = 1024 mod 7 = 2
You can verify: 1024 ÷ 7 = 146 remainder 2. The tool arrives at this without
ever computing 1024 explicitly.
Where this operation appears in practice
RSA encryption — decryption of a ciphertext c with private exponent d and
modulus n is computed as c^d mod n. The private key exponent d can be
hundreds of digits; without fast modular exponentiation, RSA would be unusable.
Diffie-Hellman key exchange — both parties compute g^x mod p with a large
prime p. The shared secret requires the same operation.
Primality testing — Miller-Rabin and Fermat primality tests both reduce to
computing a^(n-1) mod n. If the result is not 1, n is composite.
Modular inverse verification — if a^(p-1) mod p = 1 for a prime p, then
a^(p-2) mod p gives the modular inverse of a.
Edge cases and notes
- A modulus of
1always yields0, since every integer is divisible by 1. - An exponent of
0always yields1(by convention, any number to the power 0 is 1). - Negative exponents would require a modular inverse and are not supported here.
- The base can be larger than the modulus; the tool reduces it first.