R
R
rd1002021-09-30 18:53:42
Algorithms
rd100, 2021-09-30 18:53:42

What is the algorithm for adding digits from a number?

With a value of 555, it should return 6, by adding the digits in the number, if there are more than 1
How does this algorithm work, why does this formula give us the correct result for any number?

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-30
@rd100

the bottom line is that the sum of the digits of a number modulo 9 is always equal to the number itself modulo 9.
This is trivially proved - in the sum of the digits each position occurs 1 time, and in the number itself - (10^k) = (99..9 + 1 ) = (9n+1) times, and this 9n disappears if we take the remainder of the division by 9.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question