
The code of interest for this task is the code that figures out the 'digitsum' of an integer n. As with most digits-of-a-number problems, we use the 'mod' operator ('%' in C and so many languages) to find the last digit and then integer divide to remove the last digit from an integer. Some folks might consider changing the number to a string, but that is just so very slow when you have a lot of numbers to process!
Here's one way to code the digit sum routine:
dsum(n) {
int sum;
do {
for (sum = 0 ; n; n /= 10) /* peel one digit each iter */
sum += n % 10; /* bottom digit */
n = sum;
} while (sum > 9);
return sum;
}
Leaving this as a simple solution:
#include <stdio.h>
#include <stdlib.h>
dsum(n) {
int sum;
do {
for (sum = 0 ; n; n /= 10)
sum += n % 10;
n = sum;
} while (sum > 9);
return sum;
}
int main() {
FILE *fin = fopen ("dsums.in", "r");
FILE *fout = fopen ("dsums.out", "w");
int a, b, d, i, count;
fscanf (fin, "%d %d %d", &a, &b, &d);
count = 0;
for (i = a; i <= b; i++)
if (dsum (i) == d) count++;
fprintf (fout, "%d\n", count);
exit (0);
}