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
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:
As well as a one line recursive solution that doesn't use the n%9 trick: