Modular Exponentiation Calculator
BigInt readyCompute a^b mod m using fast binary exponentiation. Handles very large integers with JavaScript BigInt, and for smaller exponents shows the step-by-step square-and-multiply procedure used in programming contests and cryptography.
Perfect for number theory, competitive programming, and understanding how RSA and Diffie–Hellman use modular arithmetic in practice.
Fast ab mod m calculator
Any integer (positive or negative). The calculator internally reduces it modulo m.
Non-negative integer exponent. Time complexity is O(log b).
Positive integer modulus (m ≥ 1). In many applications m is prime or a product of primes.
Quick examples
What is modular exponentiation?
In modular arithmetic we work with integers modulo some positive integer \(m\). The expression \[ a^b \bmod m \] means that we first take the integer power \(a^b\) and then reduce it modulo \(m\) (i.e. take the remainder after division by \(m\)).
Naively, computing \(a^b\) and then reducing it is impossible for large \(b\): the intermediate result would have thousands of digits or more. Instead, modular exponentiation algorithms reduce modulo \(m\) at every step, keeping all intermediate values within the range \(\{0,\dots,m-1\}\).
Binary (square-and-multiply) algorithm
A standard way to compute \(a^b \bmod m\) is the binary exponentiation (or square-and-multiply) algorithm. Write the exponent \(b\) in binary:
Then we process the bits from left to right:
\( \quad \text{result} \leftarrow \text{result}^2 \bmod m\)
\( \quad \text{if } b_i = 1 \text{ then } \text{result} \leftarrow \text{result} \cdot a \bmod m \)
This uses O(\(\log b\)) multiplications, instead of \(b-1\) multiplications for the naive method. That is why it is the workhorse behind cryptographic schemes and competitive programming solutions.
Why modular exponentiation matters
- Cryptography – RSA, Diffie–Hellman, ElGamal, and many signature schemes rely on computing \(a^b \bmod m\) for very large integers.
- Number theory – tools like Fermat’s little theorem and Euler’s theorem use modular exponentiation to study structure in \(\mathbb{Z}_m\).
- Programming – problems involving combinatorics “mod 10⁹+7” or “mod 998244353” are standard in contests; you almost never compute \(a^b\) directly.