If a number is given as an input find sum of all the digits of number till that number
For example 11 is input then answer is 1+2….+9+(1+0)+(1+1)
The Brute-force method would be to calculate sum of digits of all the numbers that are less than a number.I have implemented that method iam wondering if there is any other way to do it without actually calculating sum of digits of every number
You can do that faster (in O(log n) operations). Let
S(n)be the sum of the digits of all numbers0 <= k < n. Thenbecause among the numbers less than
10*n, eachk < nappears as the initial part of a number 10 times, with last digits0, 1, ..., 9. So that contributes 45 for the sum of the last digits, and 10 times the sum of the digits ofk.Reversing that, we find
where
DS(k)is the plain digit sum ofk. The first two terms come from the above, the remaining two come from the sum of the digits ofn - n%10, ..., n - n%10 + (n%10 + 1).Start is
S(n) = 0forn <= 1.To include the upper bound, call it as
S(n+1).