[UVA][math] 12517 - Digit Sum
Digit Sum
Digit Sum |
The security system for Associated Computer Informatics Systems (ACIS) has aninteresting test to check the identity for authorized personal. These persons have got a piece ofsoftware that allowed them to calculate, given two integer positive numbers M and N, what is thesum of the decimal digits in the sequence M, M + 1, ..., N. Then, when somebody istrying to access ACIS system, he/she is asked to answer the question of the sum for some M and Nthat are provided at that moment, by means of the given software.
ACIS programmers have developed a rather naïve algorithm only to verify that themethod calculates the right answer. Now they are interested in developing a faster algorithm, inorder to stop unauthorized users (who may be detected because they do not answer the sum questionfast enough). And then you have been hired to help ACIS programmers to find such a method.
Input
The problem input consists of several cases, each one defined by a line with two integernumbers, M and N, without leading blanks and separated by a blank. You may assume that1 M N 109. The end of the input is signaled by a line with two zerovalues.
Output
For each case, output a line with the sum of the decimal digits for the sequenceM, M + 1, ..., N.
Sample Input
3 8
5 18
1 50
0 0
Sample Output
33
80
330
#include <stdio.h>
#define LL long long
LL calc(LL n, LL dep, LL lef) {
if(n == 0) return 0;
LL m = n%10;
return n/10*45*dep + m*lef + m*(m-1)/2*dep + calc(n/10, dep*10, lef+m*dep);
}
int main() {
int m, n;
while(scanf("%d %d", &m, &n) == 2 && n)
printf("%lld\n", calc(n,1,1)-calc(m-1,1,1));
return 0;
}