Skip to content

Instantly share code, notes, and snippets.

@johnstew
Created April 3, 2013 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save johnstew/5301736 to your computer and use it in GitHub Desktop.
Save johnstew/5301736 to your computer and use it in GitHub Desktop.
JS Digital Root
function root(num){
var total = 0;
if(num.toString().length == 1){
var iNum = parseInt(num);
return iNum;
}else{
num.toString().split("").forEach( function(value){
var iValue = parseInt(value);
return total += iValue;
});
return root(total);
}
}
@vicki8g
Copy link

vicki8g commented Jan 27, 2017

this was the best answer
function digital_root(n) {
return (n - 1) % 9 + 1;
}

n-1 means the last element
% modulus for the remainder

@lockjohn
Copy link

function digitalRoot(num) {
if (num < 10 ) return num;
return digitalRoot(Math.floor(num/10)) + num % 10;
}

@nick3499
Copy link

nick3499 commented Jan 28, 2019

came across something in a Python coding challenge. If n == 0 then that equation will return 9

def digital_root(n):
    if n == 0:
        return 0
    else:
        return (n-1) % 9 + 1
print(digital_root(0), 0)
print(digital_root(16), 7)

also in Ruby...

def digital_root(n)
  if n === 0
    return 0
  else
    return (n-1) % 9 + 1
  end
end

@br0wsa
Copy link

br0wsa commented Oct 26, 2022

function digitalRoot(n) {
return n % 9;
}
that's it

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