1. Reduce base
Take the base modulo m up front to keep numbers small.
base = base % modTyporithm · medium
Step 1 of 8 · intro card
Math & Number Theory
Square-and-multiply: fold the base in on each set exponent bit, taking the modulus after every product.
Computing base^exp directly overflows fast, so the modulus is applied throughout.
Binary exponentiation squares the base each step and multiplies it into the result on a 1 bit.
Reducing modulo m after every multiply keeps all intermediate values bounded.
Square the base each step.
Multiply in on odd exponent bits.
Reduce mod m after every product.
function modPow(base, exp, mod) {
let result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 === 1) {
result = (result * base) % mod;
}
exp = Math.floor(exp / 2);
base = (base * base) % mod;
}
return result;
}Connect each part of the code to the concept before you type.
Take the base modulo m up front to keep numbers small.
base = base % modWhen the current exponent bit is 1, fold the base into the result.
if (exp % 2 === 1)Apply the modulus after every multiply to prevent overflow.
result = (result * base) % modMove to the next exponent bit by halving.
exp = Math.floor(exp / 2)Square the base each step, reduced modulo m.
base = (base * base) % modRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input3^13 mod 17
Follow temporary values, local state and supporting structures at this step.
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state