DEV Community

Discussion on: Daily Challenge #264 - Digital Root

Collapse
 
dry profile image
Hayden Mankin

I've always liked this problem because of the n%9 trick, it's such a neat mathematical property.

I thought I'd do the obligatory n%9 solution:

let digital_root = (n) => n == 0 ? 0 : (n - 1) % 9 + 1;

console.log(digital_root(456)); // 6
console.log(digital_root(16));  // 7

As well as a one line recursive solution that doesn't use the n%9 trick:

let digital_root = (n) => (n < 10) ? n : digital_root(Array.from(n.toString()).map(Number).reduce((a, b)=>a+b));

console.log(digital_root(456)); // 6
console.log(digital_root(16));  // 7