Emmanuel Akinfulubi

JavaScriptMath

Casting out nines in JavaScript

Beginner · 4 min read

Long before calculators, accountants had a quick way to catch mistakes in a long multiplication. They added up the digits of each number, again and again, until only one digit was left, and compared the results. The trick is called casting out nines, and it still shows up in check digits, puzzles and coding interviews.

In this tutorial you will add up the digits of a number two ways, with a string and with arithmetic, and find a number where the string way breaks. Then you will reduce a number to a single digit with a loop, and replace that loop with a one-line formula. You need to know %, while loops and arrow functions.

Digit sums and digital roots

The digit sum of 493193 is 4 + 9 + 3 + 1 + 9 + 3 = 29.

Keep going: 29 gives 2 + 9 = 11, and 11 gives 1 + 1 = 2. The single digit you end on, 2, is called the digital root.

Getting digits with arithmetic

You don't need a string to read digits. Two operations do it:

  • x % 10 is the last digit. 493193 % 10 is 3.
  • Math.floor(x / 10) drops the last digit. 493193 becomes 49319.

Repeat until nothing is left and you have visited every digit, right to left.

Here is the exercise. If you want to try it on your own first, go ahead. Otherwise, read on and we will build it together.

91 Digit sums, digital roots and casting out nines

easy

Sum the digits of a number two ways, by string and by arithmetic, and find an input where the string version fails. Then reduce a number to a single digit by repeated summing, and replace that loop with a one-line formula.

Stuck? Three hints, smallest first
  1. 1. x % 10 gives the last digit and Math.floor(x / 10) drops it.
  2. 2. Above 1e20 a number no longer prints as a row of digits.
  3. 3. A digit sum leaves the remainder mod 9 unchanged, which is the whole trick.

Step 1: digit sum by arithmetic

Step 1

const digitSum = (n) => {
  let x = Math.abs(n);
  let total = 0;
  while (x > 0) {
    total += x % 10;
    x = Math.floor(x / 10);
  }
  return total;
};
console.log([0, 9, 18, 493193, 12345].map(digitSum)); // [ 0, 9, 9, 29, 15 ]

Math.abs removes a minus sign first, so -18 works too. The loop adds the last digit, drops it, and stops when x reaches 0.

Step 2: digit sum by string

The version most people write first turns the number into text and adds up the characters.

Step 2

const digitSumByString = (n) => String(Math.abs(n)).split('').reduce((s, d) => s + Number(d), 0);
console.log([0, 9, 18, 493193, 12345].map(digitSumByString)); // [ 0, 9, 9, 29, 15 ]

split('') breaks the text into single characters, and reduce adds each one after turning it back into a number. Same answers so far.

Step 3: where the string version breaks

Step 3

console.log(String(1e21));          // 1e+21
console.log(digitSumByString(1e21)); // NaN
console.log(digitSum(1e21));         // 1

From 1e21 upward, JavaScript writes numbers in exponent form. The string "1e+21" contains e and +, which are not digits, and Number('e') is NaN. So the whole sum becomes NaN. The arithmetic version has no such problem: 1e21 is a 1 followed by 21 zeros, and its digit sum is 1.

Step 4: digital root with a loop

Step 4

const digitalRootByLoop = (n) => {
  let x = Math.abs(n);
  while (x > 9) x = digitSum(x);
  return x;
};
console.log([0, 9, 18, 493193, 12345].map(digitalRootByLoop)); // [ 0, 9, 9, 2, 6 ]

Keep summing while there is more than one digit.

Step 5: the shortcut

Here is the clever part. Adding up the digits never changes a number's remainder when divided by 9. That's because 10 is 9 + 1, so 10, 100, 1000 and so on each leave a remainder of 1 when divided by 9. A number like 493193 is 4 * 100000 + 9 * 10000 + ..., and every power of ten counts as just 1. So the digital root is the remainder after dividing by 9.

There is one catch: a multiple of 9 has a root of 9, not 0. The formula 1 + ((n - 1) % 9) handles that.

Step 5

const digitalRoot = (n) => (n === 0 ? 0 : 1 + ((Math.abs(n) - 1) % 9));
console.log(digitalRoot(493193), digitalRoot(27), 27 % 9); // 2 9 0

27 % 9 is 0, but its digital root is 9. The formula shifts by one, takes the remainder, and shifts back, so the answers run 1 to 9 instead of 0 to 8. 0 is handled on its own, because it is the only number with a root of 0.

Step 6: check the shortcut against the loop

Step 6

const agreeUpTo = (limit) => {
  for (let n = 0; n <= limit; n++) if (digitalRootByLoop(n) !== digitalRoot(n)) return false;
  return true;
};
console.log(agreeUpTo(2000)); // true

The loop and the formula agree for every number from 0 to 2000.

Step 7: casting out nines

Because the digit sum keeps the remainder by 9, a number divides by 9 exactly when its digit sum does.

Step 7

console.log([126, 999, 1000].map((n) => digitSum(n) % 9 === 0)); // [ true, true, false ]
console.log([126, 999, 1000].map((n) => n % 9 === 0));           // [ true, true, false ]

To check a multiplication like 123 * 45 = 5535 by hand: the roots of 123 and 45 are 6 and 9, and 6 * 9 = 54 has root 9. The root of 5535 is also 9, so the answer passes. A wrong answer usually fails this test, but about one in nine slip through, so it can catch mistakes but never prove an answer right.

The full solution

The answer panel has both digit sums, both digital roots, persistence (how many rounds of summing a number needs) and a digit reverser with a palindrome test, and prints every case above. Press Run to see the output.

The answer

const digitSum = (n) => {
  let x = Math.abs(n);
  let total = 0;
  while (x > 0) {
    total += x % 10;
    x = Math.floor(x / 10);
  }
  return total;
};

const digitSumByString = (n) => String(Math.abs(n)).split('').reduce((s, d) => s + Number(d), 0);

const digitalRootByLoop = (n) => {
  let x = Math.abs(n);
  while (x > 9) x = digitSum(x);
  return x;
};

// Casting out nines: the root is n mod 9, with 9 in place of 0.
const digitalRoot = (n) => (n === 0 ? 0 : 1 + ((Math.abs(n) - 1) % 9));

const agreeUpTo = (limit) => {
  for (let n = 0; n <= limit; n++) if (digitalRootByLoop(n) !== digitalRoot(n)) return false;
  return true;
};

const persistence = (n) => {
  let x = Math.abs(n);
  let steps = 0;
  while (x > 9) {
    x = digitSum(x);
    steps++;
  }
  return steps;
};

const reverseDigits = (n) => {
  let x = Math.abs(n);
  let out = 0;
  while (x > 0) {
    out = out * 10 + (x % 10);
    x = Math.floor(x / 10);
  }
  return n < 0 ? -out : out;
};
const isPalindrome = (n) => n >= 0 && reverseDigits(n) === n;

console.log('digit sums       :', [0, 9, 18, 493193, 12345].map(digitSum));
console.log('by string        :', [0, 9, 18, 493193, 12345].map(digitSumByString));
console.log('1e21 prints as   :', String(1e21), '-> by string:', digitSumByString(1e21), 'by arithmetic:', digitSum(1e21));
console.log('roots by loop    :', [0, 9, 18, 493193, 12345, 999999999].map(digitalRootByLoop));
console.log('roots by formula :', [0, 9, 18, 493193, 12345, 999999999].map(digitalRoot));
console.log('27 and 28 mod 9  :', digitalRoot(27), 27 % 9, digitalRoot(28), 28 % 9);
console.log('persistence      :', persistence(9), persistence(199), persistence(999999999999));
console.log('reversed         :', reverseDigits(12345), reverseDigits(-120));
console.log('palindromes      :', [121, 12321, 123, 10].map(isPalindrome));

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.

9 checks

test('the digit sums of 0, 9, 18, 493193 and 12345', [0, 9, 18, 493193, 12345].map(digitSum), [0, 9, 9, 29, 15]);
test('the string version agrees, for numbers that print as a row of digits', [0, 9, 18, 493193, 12345].map(digitSumByString), [0, 9, 9, 29, 15]);
test('1e21 prints in exponential form, so the string version returns NaN', [String(1e21), Number.isNaN(digitSumByString(1e21)), digitSum(1e21)], ['1e+21', true, 1]);
test('the digital root is the digit sum applied until one digit is left', [0, 9, 18, 493193, 12345, 999999999].map(digitalRootByLoop), [0, 9, 9, 2, 6, 9]);
test('and 1 + (n - 1) % 9 gives the same answer for every n up to 2000', agreeUpTo(2000), true);
test('so the root is n mod 9, except that a multiple of 9 has root 9 not 0', [digitalRoot(27), 27 % 9, digitalRoot(28), 28 % 9], [9, 0, 1, 1]);
test('casting out nines: divisibility by 9 shows up in the digit sum', [[126, 999, 1000].map((n) => digitSum(n) % 9 === 0), [126, 999, 1000].map((n) => n % 9 === 0)], [[true, true, false], [true, true, false]]);
test('persistence counts the rounds, and a trillion nines needs only two', [persistence(9), persistence(199), persistence(999999999999)], [0, 3, 2]);
test('reversing drops trailing zeros, so 120 comes back as 21', [reverseDigits(12345), reverseDigits(-120), [121, 12321, 123, 10].map(isPalindrome)], [54321, -21, [true, true, false, false]]);

Two ways to get at digits, and they fail differently. The string version reads well and works up to about 1e20; above that String(1e21) is '1e+21', Number('e') is NaN, and the whole sum becomes NaN. The arithmetic version — x % 10 then Math.floor(x / 10) — has no such cliff, and it is faster because it allocates nothing.

The digital root is a shortcut hiding in plain sight. Summing digits does not change a number's remainder mod 9, because 10 is 1 more than 9 and every power of 10 is therefore 1 mod 9. So repeatedly summing must land on the remainder mod 9 — with the single adjustment that a multiple of 9 lands on 9 rather than 0. 1 + ((n - 1) % 9) encodes that adjustment, and it agrees with the loop for every value tested. Note it needs the n === 0 case handled separately, since 1 + ((-1) % 9) would be 0 by accident rather than by design.

This is the old accountant's check called casting out nines: if the digit sums of two numbers do not agree with the digit sum of their product, the multiplication is wrong. It cannot prove an answer right, since one in nine wrong answers passes, but it is very cheap.

Common mistakes

  • Summing digits through String for any size of number. From 1e21 the string has an exponent in it and the sum is NaN. Use % 10.
  • Writing the root as n % 9. Multiples of 9 come out as 0 instead of 9. Use 1 + ((n - 1) % 9) and treat 0 on its own.
  • Using casting out nines as proof. It catches most wrong answers, but about one in nine pass anyway.

Try it yourself

  1. Check 234 * 56 = 13104 with casting out nines. Then change one digit of the answer and check again.
  2. Write digitCount(n) using % 10 and Math.floor, and compare it with String(n).length for 1e21.
  3. Swap two digits of a number, like 4931 to 9431. Does the digital root change? Explain why.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.