Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Math

Climb in Doubling Jumps.

Watch the explainer

Don't memorize fast power — watch the exponent climb in doubling jumps. To find a^b mod m you never multiply b times. You square the base to reach a, a², a⁴, a⁸ … — each squaring doubles the reach — and then multiply into the answer only the powers the binary digits of b pick out. That is O(log b) multiplications instead of b, and taking the mod after every step keeps the numbers tiny. It is the engine inside RSA.

square the base · read b in binary · multiply on set bits · mod every step
FAST POWER

Reach a^b in about log b multiplications, not b.

SQUARING

Square the base repeatedly: a, a², a⁴, a⁸ … each step doubles the exponent reached.

BINARY EXPONENT

The bits of b choose which squared powers get multiplied into the result.

MOD EACH STEP

Apply mod m after every multiply so values never blow up.

fastpow.sim — 3¹³ mod 7 · 13 = 1101₂
Ready

Compute 3¹³ mod 7. Since 13 = 1101₂, we need 3¹ · 3⁴ · 3⁸ (the set bits). Press Step: square the base for each bit position and multiply it in only where the bit is 1.

result = 1, base = a; per bit: if bit: result = result·base mod m; base = base² mod m
1
Result mod 7
0 / 4
Bits done

Every exponent is a sum of powers of two

The whole trick rests on binary. Thirteen is 1101₂ = 8 + 4 + 1, so 3¹³ = 3⁸ · 3⁴ · 3¹. You never need 3², 3³, 3⁵ and the rest — just the powers whose bit is set. And the powers you do need form a doubling ladder you can climb by squaring: 3¹ → 3² → 3⁴ → 3⁸, each rung one multiplication. So you walk the bits of the exponent from the least significant, keep a base that squares each step, and fold it into a running result whenever the current bit is 1. Take mod 7 after every multiply and the base sequence stays small — 3, 2, 4, 2 — never the astronomical 3¹³ = 1 594 323.

01

Decompose the exponent

b in binary is a sum of powers of two, so a^b is a product of a^(2^i) over the set bits.

02

Square the base

Start base = a; each step base = base² mod m, giving a, a², a⁴, a⁸ …

03

Multiply on set bits

If the current bit is 1, fold it in: result = result · base mod m. Skip it if the bit is 0.

04

Shift to the next bit

b >>= 1 and repeat until b = 0 — about log₂(b) rounds.

Time
O(log b)
Space
O(1)
This example
4 vs 12
Uses
RSA · DH

For 3¹³ the naive method does 12 multiplications; squaring does 4. That gap explodes with size: raising to a 2048-bit exponent, as RSA does, would be an impossible 2²⁰⁴⁸ multiplications naively, but only about 2048 by squaring. This is exactly why public-key cryptography is practical — RSA, Diffie–Hellman key exchange, and Fermat/Miller–Rabin primality tests all lean on fast modular exponentiation. Pair it with the extended Euclidean algorithm for modular inverses and you have the arithmetic core of modern encryption.

Check yourself

1 · How many multiplications does fast power need for a^b?

Squaring reaches a^(2^i) in i steps, and the binary exponent has only about log₂(b) bits — so a handful of multiplications suffice.

2 · What does one squaring do to the power the base represents?

Squaring a^k gives a^(2k), so the exponent you can represent doubles each step — that is the doubling ladder.

3 · Why take mod m after every multiplication?

Modular arithmetic is compatible with multiplication, so applying mod each step keeps numbers below m without changing the result.

The picture: six squarings stand in for 44 multiplications

bit i of 45 (lowest first) 101101 base = 7^(2^i) mod 13, squared each step 7109393 result after step i (multiply base in only where the bit is 1) 7711778 7^45 mod 13 = 8: 5 squarings, 4 multiplies, not 44
Highlighted columns are the 1 bits of 45; shaded columns are bits that are 0, where the squared base is computed but not used. The middle row is only ever a number below 13, even though 7^45 itself has 39 digits.

Worked example, step by step

Compute 7^45 mod 13. Keep result = 1 and base = 7. While the exponent is non-zero: if its lowest bit is 1, set result = result × base mod 13; then square the base mod 13 and shift the exponent right one bit.

StepExponent eLow bitbaseresult beforeresult after
0451717
12201077
21119711
3513117
420977
511378

Read the base column: 7, 10, 9, 3, 9, 3 are 7^1, 7^2, 7^4, 7^8, 7^16, 7^32 mod 13, each made by squaring the one before. The 1 bits of 45 (32 + 8 + 4 + 1) pick out 7^1 · 7^4 · 7^8 · 7^32, which is 7 × 9 × 3 × 3 mod 13 = 8. That is 5 squarings and 4 multiplies, 9 operations in total, against 44 for the plain loop. The saving is the reason the idea scales: the work depends on the number of bits of the exponent, not its size. The base also cycles (9, 3, 9, 3) because powers modulo a prime repeat, a pattern the algorithm never needs to notice.

Complexity and trade-offs

CaseTimeSpaceWhy
Square-and-multiplyO(log b) multiplicationsO(1) numbersAt most ⌊log₂ b⌋ squarings plus one multiply per 1 bit. About half the bits are 1 on average.
Multiply b times, reducing mod mO(b) multiplicationsO(1)44 steps for exponent 45; for a 2048-bit exponent it is not computable in the lifetime of the universe.
Compute a^b, then take % mgrows with the size of a^bO(b log a) bits7^45 already has 39 digits. Correct in Python, hopeless in fixed-width integers.
Left-to-right (high bit first)O(log b)O(1)Same operation count; multiplies by the small original base, which helps when the base is tiny.
Reduce the exponent first (prime m)O(log m) after reductionO(1)For prime m and gcd(a, m) = 1, a^b = a^(b mod (m−1)) mod m by Fermat’s little theorem. Cuts huge b down to size.

In cryptography the cost unit is not “one multiply” but one multiplication of k-bit numbers, which grows with k. A 2048-bit RSA private exponent needs about 2,048 squarings and, on average, about 1,024 multiplies, each on 2,048-bit numbers. The public exponent 65,537 is 2^16 + 1, which is 16 squarings and one multiply, which is why encryption and signature verification are far cheaper than decryption and signing. The cost to watch is the modulus size, since every step is a big-number multiply followed by a reduction.

Common mistakes

  • Forgetting to reduce inside the loop

    Squaring without % m grows the base as 7, 49, 2401, 5,764,801 … doubling its digit count each step; in 64-bit integers it wraps around by the fifth squaring (7^32) and the answer is garbage that looks plausible.

  • Overflow in the product itself

    Even with the mod, result × base is computed before it is reduced. For m = 10^9 + 7 the product stays below 1.0e18 and fits in a signed 64-bit integer; for a modulus above about 3.04e9 it can exceed 2^63 − 1. Use 128-bit intermediates or a mulmod routine.

  • Not reducing the starting base

    If a ≥ m (say a = 10^12, m = 7), the first squaring is already huge. Start with base = a % m.

  • Starting result at 1 when m is 1

    Everything is 0 modulo 1, including a^0, so pow(5, 0, 1) is 0. A loop that returns the initial result = 1 for exponent 0 answers 1. Return result % m.

  • Branching on secret bits

    The if bit makes some steps slower than others, so timing leaks the exponent. That is a real attack on naive RSA implementations. Cryptographic code uses constant-time forms such as the Montgomery ladder; this version is fine for contests and non-secret exponents.

Where this shows up

  • RSA and Diffie-Hellman

    RSA encryption, decryption and signing are each one modular exponentiation with a 2048-bit (or larger) modulus, and a Diffie-Hellman key exchange is two. None would be feasible without square-and-multiply.

  • Primality testing

    The Miller–Rabin test raises a random base to n − 1-derived powers modulo n and examines the intermediate squarings. It is how crypto libraries find the large primes they generate keys from.

  • Built-ins

    Python’s three-argument pow(a, b, m) does exactly this and is the idiomatic way to write it; (a ** b) % m builds the full power first and is vastly slower for large b.

  • Modular inverses in contests

    For a prime modulus p, the inverse of a is a^(p−2) mod p by Fermat’s little theorem, which is how combinatorics answers mod 10^9 + 7 divide by factorials.

SOLVE IT YOURSELF

Solve it: fast modular exponentiation

Computing 2^1000 mod p by multiplying a thousand times is hopeless — and unnecessary. Square your way there in ~10 steps instead. Runs for real in your browser.

YOUR TASK

Implement mod_pow(base, exp, mod) — that is (base ** exp) % mod — without ever building the full power. Use exponentiation by squaring, and handle exp = 0 and mod = 1.

HINTS — 6 IDEAS
  1. Read the exponent in binary. 2^13 = 2^8 · 2^4 · 2^1 — only the set bits contribute.
  2. Keep squaring the base (base = base² mod m), which walks it through b, b², b⁴, b⁸ …
  3. Whenever the current bit of the exponent is 1, fold that power into the result.
  4. Take % mod after every multiply, never at the end — that is what keeps the numbers small.
  5. mod = 1 is a special case: everything is congruent to 0. And any base to the power 0 is 1.
  6. This is O(log exp), not O(exp) — it is what makes RSA and Diffie-Hellman practical.
CPython · WebAssembly

Questions

Why is this so important for cryptography?

RSA and Diffie–Hellman raise huge numbers to huge powers modulo a large modulus. Naively that is an impossible number of multiplications; fast modular exponentiation reduces it to roughly the bit-length of the exponent, which is what makes public-key crypto feasible at all.

Recursive or iterative?

Both work. Recursive: pow(a,b) = pow(a, b/2)², times an extra a when b is odd. Iterative: scan the exponent bits, squaring the base and multiplying on set bits. The iterative bit-scan uses O(1) extra space.

What about overflow?

Intermediate products can be as large as (m − 1)², so use a wide integer type (64-bit) or big-integers for cryptographic sizes. Because you mod after each multiply, the stored values themselves always stay below m.

A few squarings beat a million multiplies.

Square the base up the doubling ladder, fold in the powers the binary exponent selects, mod every step — a^b mod m in log time.

▶  Watch it explained

Modular Exponentiation: 1.2 Billion Pulls in 44 Steps

Finished this one? 0 / 99 Algorithms done
NextSieve of Eratosthenes: Prime Time Next on the “Number theory, in order” ladder · rung 4 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms