Number a (Base)
Number b (Exponent)
Number n (Modulus)

Description

Modular Exponentiation: Modular exponentiation refers to efficiently calculating the value of (a^b mod n). Direct computation of a^b imposes massive computational overhead. Since the exponent (b) can be extremely large, the raw result of a^b will become astronomically huge and exceed the processing limits of computers. The core purpose of modular exponentiation is to efficiently compute (a raised to the power b, modulo n).
The most common implementation is the fast exponentiation algorithm (Exponentiation by Squaring), which completes calculations with a time complexity of O(log b). Its core logic leverages the binary representation of exponents to reduce multiplication operations and boost performance. Detailed steps are listed below:
1. Convert the exponent (b) into its binary form.
2. Process each binary bit from the most significant bit to the least significant bit: Multiply the result by the current base (a) if the current bit equals 1. Take modulo n after every multiplication to restrain intermediate values. Right-shift the exponent (equivalent to integer division by 2), then square the base.
Fast Exponentiation Algorithm (Simple JavaScript Implementation)
function mod_pow(base, exponent, modulus) {
    let result = 1;
    while (exponent > 0) {
        // If exponent is odd, multiply result by base then take modulo
        if (exponent % 2 === 1) {
            result = (result * base) % modulus;
        }
        // Right shift exponent = integer division by 2
        exponent = exponent >> 1;
        // Square the base and take modulo
        base = (base * base) % modulus;
    }
    return result;
}
This method efficiently computes a^b mod n, ideal for scenarios involving huge integers and oversized exponents, such as the RSA algorithm and Diffie-Hellman key exchange in cryptography.
Notes
The modulus must be greater than 0; primes or products of two primes are standard choices in cryptography.
Use BigInt for large integer calculations to avoid numeric overflow and precision loss.
Exponentiation by squaring runs at O(log n), making it highly efficient for large-number computation.
Exponents and moduli in real-world cryptography are often hundreds of digits long.
Modular exponentiation is a one-way function: trivial to compute forward, yet computationally infeasible to reverse (Discrete Logarithm Problem).