Skip to content

Instantly share code, notes, and snippets.

@bullishgopher
Created April 20, 2023 16:18
Show Gist options
  • Save bullishgopher/b4adbf56b5f108ee69eca08eed6c8c67 to your computer and use it in GitHub Desktop.
Save bullishgopher/b4adbf56b5f108ee69eca08eed6c8c67 to your computer and use it in GitHub Desktop.
Sum of Digits / Digital Root

Digital root is the recursive sum of all the digits in a number.

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

Examples

    16  -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2

My Solution

function digital_root(n) {
  return (n - 1) % 9 + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment