Dynamic Programming21 sections · 916 units
Open in Course

Sum of Digits - Recursive Formula

Last digit + rest

The recursive formula is: sum(n)=(nmod10)+sum(n/10)\text{sum}(n) = (n \bmod 10) + \text{sum}(\lfloor n / 10 \rfloor) This says: the sum of digits equals the last digit plus the sum of the remaining digits.

For example, sum(1234)=4+sum(123)\text{sum}(1234) = 4 + \text{sum}(123), and sum(123)=3+sum(12)\text{sum}(123) = 3 + \text{sum}(12), continuing until you reach a single digit. Each recursive call shrinks nn by removing its last digit, moving you toward the base case.