Luke a Pro

Luke Sun

Developer & Marketer

๐Ÿ‡บ๐Ÿ‡ฆ

Binary Exponentiation

| , 6 minutes reading.

Binary Exponentiation (Fast Power)

Introduction: The Trillion-Step Problem

Suppose you need to calculate 31,000,000,000,0003^{1,000,000,000,000} (3 to the power of 1 trillion).

  • Naive Loop: Multiply 3 * 3 * 3... one trillion times. This takes forever.
  • Binary Exponentiation: Calculate it in about 40 steps.

This algorithm is the cornerstone of modern cryptography (RSA, Diffie-Hellman), where calculating powers of massive numbers modulo a prime is the standard operation.

What Problem does it solve?

  • Input: Base aa, Exponent nn, and usually a Modulo mm.
  • Output: (an)%m(a^n) \% m.
  • The Promise: Calculates the result in O(logโกn)O(\log n) multiplications instead of O(n)O(n).

Core Idea (Intuition)

Use the binary representation of the exponent. 310=3(1010)2=38โ‹…323^{10} = 3^{(1010)_2} = 3^8 \cdot 3^2. Instead of multiplying 3 ten times, we can:

  1. Calculate 31=33^1 = 3.
  2. Square it to get 32=93^2 = 9.
  3. Square it to get 34=813^4 = 81.
  4. Square it to get 38=65613^8 = 6561.
  5. Combine the parts we need (383^8 and 323^2) based on the binary bits of 10.

How it Works

  1. Initialize result = 1.
  2. While n>0n > 0:
    • If nn is odd (last bit is 1), multiply result by current base aa.
    • Square the base (a=aโ‹…aa = a \cdot a).
    • Divide nn by 2 (shift right).

Typical Business Scenarios

  • โœ… Cryptography: RSA encryption requires calculating C=Me(modN)C = M^e \pmod N where ee is huge.
  • โœ… Matrix Powers: Calculating the nn-th Fibonacci number in O(logโกn)O(\log n) by using matrix exponentiation.
  • โœ… Combinatorics: Calculating Modular Inverse (apโˆ’2(modp)a^{p-2} \pmod p) for combinations (nk){n \choose k}.

Code Demo (TypeScript)

function modPow(base: bigint, exp: bigint, mod: bigint): bigint {
    let result = 1n;
    base = base % mod;

    while (exp > 0n) {
        // If exp is odd, multiply base with result
        if (exp % 2n === 1n) {
            result = (result * base) % mod;
        }
        // Square the base
        base = (base * base) % mod;
        // Divide exp by 2
        exp = exp / 2n;
    }
    return result;
}

Performance & Complexity

  • Time: O(logโกn)O(\log n).
  • Space: O(1)O(1).

Summary

โ€œBinary Exponentiation is the art of doubling. By squaring the base repeatedly, it traverses the exponent exponentially fast, turning impossible calculations into instant ones.โ€