Modular exponentiation in JavaScript
Advanced · 5 min read
What is the remainder when 7 to the power 100 is divided by 13? The obvious code, 7 ** 100 % 13, gives 3. The right answer is 9. The power is a number with 85 digits, far too big to store exactly, so the remainder is worked out from a rounded value and comes out wrong.
In this tutorial you will learn modular exponentiation: a way to find that remainder without ever computing the giant power. Then you will learn the extended Euclidean algorithm, which finds a "modular inverse", the closest thing remainder arithmetic has to division. These two functions are the heart of RSA encryption. To finish, you will use the same arithmetic to build an ISBN book-number check digit and see why the card-number check (Luhn) misses an error that ISBN catches. You need to know while loops and %.
Arithmetic with remainders
"Modulo m" means you only care about the remainder after dividing by m. Clocks work like this: 9 o'clock plus 5 hours is 2 o'clock, because 14 mod 12 is 2.
The key fact is that you can take the remainder at any point and the final remainder doesn't change. (7 * 7) mod 13 is the same as ((7 mod 13) * (7 mod 13)) mod 13. So you can keep every number small while you work.
A true mod for negative numbers
JavaScript's % keeps the sign of the left side, so -3 % 11 is -3. For this exercise you want a result from 0 to m - 1, so the answer wraps it:
const mod = (a, n) => ((a % n) + n) % n;
console.log(-3 % 11, mod(-3, 11)); // -3 8
Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.
105 Modular exponentiation, inverses, and a check digit that works
hardRaise a number to a large power modulo something, without ever computing the power. Compare it with the naive base ** exponent % m. Then find modular inverses with the extended Euclidean algorithm, and use mod 11 arithmetic to build an ISBN-10 check digit — and show what Luhn's mod 10 version misses.
Stuck? Three hints, smallest first
- 1. Square and multiply: halve the exponent each round and reduce mod
mevery step. - 2. The extended algorithm tracks the coefficients
xandywitha x + b y = gcd(a, b). - 3. An inverse exists only when the two numbers are coprime.
Step 1: see the naive version fail
console.log(7 ** 100 % 13); // 3
console.log(String(7n ** 100n % 13n)); // 9
console.log(7 ** 1000, 7 ** 1000 % 13); // Infinity NaN
BigInt does the whole calculation exactly and confirms 9. At the power 1000, the number is too big even for a rounded double. It becomes Infinity, and the remainder of Infinity is NaN, "not a number".
Step 2: square and multiply
The trick is to halve the exponent instead of counting it down. 7 to the 100 is (7 to the 50) squared, and 7 to the 50 is (7 to the 25) squared. When the exponent is odd, peel off one 7 into the result first.
const powMod = (base, exponent, m) => {
let result = 1;
let b = mod(base, m);
let e = exponent;
while (e > 0) {
if (e % 2 === 1) result = (result * b) % m;
b = (b * b) % m;
e = Math.floor(e / 2);
}
return result;
};
console.log(powMod(2, 10, 1000), powMod(7, 100, 13)); // 24 9
Each loop squares b, halves e, and multiplies b into the result whenever e is odd. The exponent 100 takes seven trips round the loop, not a hundred. Every value is reduced mod m, so nothing grows past m squared.
That is also this version's limit. b * b must stay below 2 ** 53 to be exact, so m has to be under about 94,906,265. Past that, use BigInt.
Step 3: Fermat's little theorem
When p is prime and a isn't a multiple of p, a to the power (p - 1) leaves remainder 1:
console.log([2, 3, 5, 6, 7].map((a) => powMod(a, 12, 13))); // [ 1, 1, 1, 1, 1 ]
console.log(powMod(2, 14, 15)); // 4
15 isn't prime, and the test gives 4 instead of 1. Real primality tests start from this idea.
Step 4: the extended Euclidean algorithm
The Euclidean algorithm finds the greatest common divisor (gcd) by replacing a pair of numbers with the smaller one and the remainder, until the remainder is 0. The extended version also tracks two numbers x and y so that a * x + b * y equals the gcd.
const egcd = (a, b) => {
let [oldR, r] = [a, b];
let [oldS, s] = [1, 0];
let [oldT, t] = [0, 1];
while (r !== 0) {
const q = Math.floor(oldR / r);
[oldR, r] = [r, oldR - q * r];
[oldS, s] = [s, oldS - q * s];
[oldT, t] = [t, oldT - q * t];
}
return [oldR, oldS, oldT];
};
console.log(egcd(240, 46), 240 * -9 + 46 * 47); // [ 2, -9, 47 ] 2
[x, y] = [y, x] swaps two values in one line. Each round does the same update to the remainders and to both coefficient pairs. The check at the end shows that 240 * -9 + 46 * 47 really is 2.
Step 5: modular inverses
The inverse of a, mod m, is the number x where a * x leaves remainder 1. When the gcd of a and m is 1, the x from egcd is exactly that number.
const modInverse = (a, m) => {
const [g, x] = egcd(mod(a, m), m);
return g === 1 ? mod(x, m) : NaN;
};
console.log(modInverse(3, 11), (3 * 4) % 11); // 4 1
console.log(modInverse(17, 3120), modInverse(6, 9)); // 2753 NaN
6 and 9 share a factor of 3, so 6 has no inverse mod 9. Returning NaN makes that obvious, where a made-up number would hide the problem.
Step 6: an ISBN-10 check digit
An ISBN-10 weights its ten digits 10, 9, 8, down to 1, and the weighted total must divide by 11. A check value of 10 is written as X.
const isbn10Weighted = (chars) => {
let total = 0;
for (let i = 0; i < chars.length; i++) {
const ch = chars[i];
total += (10 - i) * (ch === 'X' ? 10 : Number(ch));
}
return total;
};
const digitsOf = (s) => s.split('').filter((ch) => ch !== '-');
const isbn10CheckDigit = (first9) => {
const c = mod(-isbn10Weighted(digitsOf(first9)), 11);
return c === 10 ? 'X' : String(c);
};
const isbn10Valid = (s) => {
const d = digitsOf(s);
return d.length === 10 && isbn10Weighted(d) % 11 === 0;
};
console.log(isbn10CheckDigit('030640615'), isbn10CheckDigit('043942089')); // 2 X
console.log(isbn10Valid('0306406152'), isbn10Valid('0306406512')); // true false
The check digit is whatever brings the total up to a multiple of 11, which is mod(-total, 11). Swapping the neighboring digits 1 and 5 is caught.
Step 7: what Luhn misses
Card numbers use the Luhn check, which works mod 10:
const luhn = (s) => {
let sum = 0;
let double = false;
for (let i = s.length - 1; i >= 0; i--) {
let d = Number(s[i]);
if (double) {
d *= 2;
if (d > 9) d -= 9;
}
sum += d;
double = !double;
}
return sum % 10 === 0;
};
console.log(luhn('4091234567890121'), luhn('4901234567890121')); // true true
Swapping the 0 and the 9 passes. Doubled, 9 becomes 18, which folds to 9, and 0 stays 0, so the pair adds 9 either way. 11 is prime, which is why the ISBN check catches every swap of two digits.
The full solution
The answer panel has mod, powMod, egcd, modInverse, the ISBN functions and luhn, and prints every case above. Press Run to see the output.
const mod = (a, n) => ((a % n) + n) % n;
// Square and multiply. Nothing ever grows past m squared.
const powMod = (base, exponent, m) => {
let result = 1;
let b = mod(base, m);
let e = exponent;
while (e > 0) {
if (e % 2 === 1) result = (result * b) % m;
b = (b * b) % m;
e = Math.floor(e / 2);
}
return result;
};
// Extended Euclid: returns [g, x, y] with a * x + b * y === g.
const egcd = (a, b) => {
let [oldR, r] = [a, b];
let [oldS, s] = [1, 0];
let [oldT, t] = [0, 1];
while (r !== 0) {
const q = Math.floor(oldR / r);
[oldR, r] = [r, oldR - q * r];
[oldS, s] = [s, oldS - q * s];
[oldT, t] = [t, oldT - q * t];
}
return [oldR, oldS, oldT];
};
const modInverse = (a, m) => {
const [g, x] = egcd(mod(a, m), m);
return g === 1 ? mod(x, m) : NaN;
};
// ISBN-10: weights 10 down to 1, and the whole thing must be 0 mod 11.
const isbn10Weighted = (chars) => {
let total = 0;
for (let i = 0; i < chars.length; i++) {
const ch = chars[i];
total += (10 - i) * (ch === 'X' ? 10 : Number(ch));
}
return total;
};
const digitsOf = (s) => s.split('').filter((ch) => ch !== '-');
const isbn10CheckDigit = (first9) => {
const c = mod(-isbn10Weighted(digitsOf(first9)), 11);
return c === 10 ? 'X' : String(c);
};
const isbn10Valid = (s) => {
const d = digitsOf(s);
return d.length === 10 && isbn10Weighted(d) % 11 === 0;
};
// Luhn: mod 10, doubling every second digit from the right.
const luhn = (s) => {
let sum = 0;
let double = false;
for (let i = s.length - 1; i >= 0; i--) {
let d = Number(s[i]);
if (double) {
d *= 2;
if (d > 9) d -= 9;
}
sum += d;
double = !double;
}
return sum % 10 === 0;
};
console.log('2 ** 10 mod 1000 :', powMod(2, 10, 1000));
console.log('7 ** 100 mod 13 :', powMod(7, 100, 13), 'naively:', 7 ** 100 % 13, 'BigInt:', String(7n ** 100n % 13n));
console.log('7 ** 1000 naively :', 7 ** 1000, '->', 7 ** 1000 % 13);
console.log('Fermat mod 13 :', [2, 3, 5, 6, 7].map((a) => powMod(a, 12, 13)));
console.log('the same on 15 :', powMod(2, 14, 15), '<- 15 is composite');
console.log('egcd(240, 46) :', egcd(240, 46), 'check:', 240 * -9 + 46 * 47);
console.log('inverses mod 11 :', Array.from({ length: 10 }, (unused, i) => modInverse(i + 1, 11)));
console.log('6 mod 9 :', modInverse(6, 9), '<- they share a factor of 3');
console.log('check digits :', isbn10CheckDigit('030640615'), isbn10CheckDigit('043942089'));
console.log('ISBN transposed :', isbn10Valid('0306406152'), isbn10Valid('0306406512'));
console.log('Luhn transposed :', luhn('4091234567890121'), luhn('4901234567890121'));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('2 to the 10 mod 1000 is 24, and 7 to the 100 mod 13 is 9', [powMod(2, 10, 1000), powMod(7, 100, 13)], [24, 9]);
test('computing the power first gives 3, and BigInt confirms 9 is the right one', [7 ** 100 % 13, String(7n ** 100n % 13n)], [3, '9']);
test('push the exponent to 1000 and the naive version overflows to NaN', [7 ** 1000 === Infinity, Number.isNaN(7 ** 1000 % 13)], [true, true]);
test('Fermat: every a coprime to 13 gives 1 when raised to the 12th mod 13', [2, 3, 5, 6, 7].map((a) => powMod(a, 12, 13)), [1, 1, 1, 1, 1]);
test('the same test on composite 15 gives 4, which is how primality tests start', powMod(2, 14, 15), 4);
test('extended Euclid finds the coefficients, and they check out', [egcd(240, 46), 240 * -9 + 46 * 47], [[2, -9, 47], 2]);
test('so 3 has inverse 4 mod 11, and every unit mod 11 has one', [modInverse(3, 11), Array.from({ length: 10 }, (unused, i) => ((i + 1) * modInverse(i + 1, 11)) % 11)], [4, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]);
test('6 has no inverse mod 9 since they share a factor; 17 mod 3120 has 2753', [Number.isNaN(modInverse(6, 9)), modInverse(17, 3120), (17 * 2753) % 3120], [true, 2753, 1]);
test('mod 11 catches the transposition; Luhn mod 10 passes 09 and 90 alike', [isbn10CheckDigit('030640615'), isbn10Valid('0306406152'), isbn10Valid('0306406512'), luhn('4091234567890121'), luhn('4901234567890121')], ['2', true, false, true, true]);
powMod is the one algorithm in this section you are likely to need and unlikely to invent. Squaring and multiplying reduces the exponent by half each round, so 7 ** 100 takes seven multiplications rather than a hundred, and reducing mod m after every one keeps every intermediate below m squared. The naive route fails in two different ways: 7 ** 100 % 13 returns 3 because 7 ** 100 is not exactly representable, and 7 ** 1000 % 13 returns NaN because the power overflowed to Infinity first. Note the one constraint on the fast version — b * b must stay exact, so m has to be below about 94,906,265. Past that, use BigInt.
The extended Euclidean algorithm carries the coefficients along with the remainders, so it ends with a x + b y = gcd(a, b). When the gcd is 1, that x is the modular inverse: it is the closest thing modular arithmetic has to division. When the gcd is not 1 there is no inverse at all, and returning NaN rather than a plausible number is the difference between a bug you find in a test and one you find in production. Everything RSA does is these two functions.
The check digits make the point about choosing a modulus. ISBN-10 weights its digits 10 down to 1 and works mod 11 — a prime — so every single-digit error and every transposition of two digits is caught. Luhn works mod 10, which is not prime, and it is blind to swapping a 0 and a 9: 4091234567890121 and 4901234567890121 both validate. That is a real property of every card number in your wallet, and it follows directly from 10 having factors.
Common mistakes
- Computing the power first.
base ** exponent % mis wrong once the power passes2 ** 53, andNaNonce it overflows. - Using
%on negative numbers.-3 % 11is -3, not 8. Use themodhelper. - Returning an inverse that doesn't exist. Check that the gcd is 1 first.
Try it yourself
- Use
powModto find the last three digits of 3 to the power 1000. (Work mod 1000.) - Write
powModBigwith BigInt so thatmcan be any size. - Find every number from 1 to 12 that has an inverse mod 12.