Skip to content

Instantly share code, notes, and snippets.

@raymondpittman
Forked from tomanistor/problem.md
Created September 9, 2020 03:37
Show Gist options
  • Save raymondpittman/ad0868b3348c3801995f214903042cf9 to your computer and use it in GitHub Desktop.
Save raymondpittman/ad0868b3348c3801995f214903042cf9 to your computer and use it in GitHub Desktop.
Sum of Digits / Digital Root

In this kata, you must create a digital root function.

A 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 two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

Here's how it works (Ruby example given):

digital_root(16)
=> 1 + 6
=> 7

digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6

digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6

digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2
function digital_root(n) {
var digits = n.toString().split("").map(Number);
var sum = 0;
for (var i = 0; i < digits.length; i++) {
sum += digits[i];
}
var sumString = sum.toString();
if (sumString.length > 1) {
var sumDigits = sumString.split("").map(Number);
var firstSumDigit = sumDigits.slice(0);
var lastSumDigit = sumDigits.slice(-1);
return firstSumDigit[0] + lastSumDigit[0];
} else {
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment