Here is a digitalRoot calculation
It will loop until the sum of the digits in the input has the length 1
The digital root (also repeated digital sum) of a natural number in a given radix is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. For example, in base 10, the digital root of the number 12345 is 6 because the sum of the digits in the number is 1 + 2 + 3 + 4 + 5 = 15, then the addition process is repeated again for the resulting number 15, so that the sum of 1 + 5 equals 6, which is the digital root of that number. Wikipedia
const digitalRoot = num => {
let len = num.toString().length;
while (len > 1) {
num = [...num.toString()].reduce((a,b) => (+a) + (+b));
len = num.toString().length;
}
return num
};
console.log(digitalRoot(11)); // 2
console.log(digitalRoot(1999)); // 1
In base 10, this is equivalent to taking the remainder upon division by 9 (except when the digital root is 9, where the remainder upon division by 9 will be 0), which allows it to be used as a divisibility rule.
const digitalRoot = num => {
if (num === 0) return 0;
if (num % 9 === 0) return 9;
return num % 9;
};
console.log(digitalRoot(11)); // 2
console.log(digitalRoot(1999)); // 1
If you want the multiplicative digitalRoot you can do this
const multiplicativeDigitalRoot = num => {
let persistence = 0;
while (num > 9) {
num = [...num.toString()].reduce((a, b) => a * b);
console.log(num)
persistence++;
}
return { root: num, persistence }; // second number is how many iterations it took
};
console.log(multiplicativeDigitalRoot(11)); // 1,1
console.log(multiplicativeDigitalRoot(1999)); // 2,4
console.log(multiplicativeDigitalRoot(277777788888899)); // 0, 11