Skip to content

Instantly share code, notes, and snippets.

@tomanistor
Created June 22, 2017 17:38
Show Gist options
  • Save tomanistor/70d7a1692a1bfc6d36169798eacba7d5 to your computer and use it in GitHub Desktop.
Save tomanistor/70d7a1692a1bfc6d36169798eacba7d5 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;
}
}
@weskhaled
Copy link

also, you can refactor this with reducer

const digital_root = n => {
return n.toString().length == 1 ? n :
digital_root(Number(n).toString().split('').reduce((acc,item) => Number(acc) + Number(item), 0))
}

@asopromadze
Copy link

asopromadze commented Apr 13, 2020

not working
weskhaled answer too :(
it stops after 2 step tryng to figure out if i can ill answer here

@asopromadze
Copy link

function digital_root(n) {
return ((n - 1) % 9) + 1;
}

@zidoxx
Copy link

zidoxx commented Jul 24, 2020

function digital_root(n){
let result = 0;
n.toString().split('').map (n => {
result += Number(n)
})
return result > 9 ? digital_root(result) : result;
}

@cihat
Copy link

cihat commented Sep 25, 2020

good solution.

Copy link

ghost commented Feb 19, 2021

const digital_root = n => {
return n !== 0 && n % 9 === 0 ? 9 : n % 9;
}

@sbardijs
Copy link

function digital_root(n) {
return +${n}.split('').reduce((x, y) => (+x) + (+y));
}

@emtiazahmed27
Copy link

function digital_root(n) { return ((n - 1) % 9) + 1; }

that was excellent! can you explain please sir!

@erfaneh-sahraei
Copy link

Hello, does your code return 1 for the number 10?

@Boqiboyev
Copy link

Thank you

@BlagodarovVA
Copy link

function digitalRoot(n) {
  if (n < 10) {
    return n;
  }

  while (n > 9) {
    var digits = String(n).split("").map(Number);
    n = digits.reduce((sum, current) => sum + current);
  }
  console.log('n - ',n);
  return n;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment