An integer is divisible by 3 if the sum of its digits is also divisible by 3. For example, 3702 is divisible
by 3 and 12(3+7+0+2) is also divisible by 3. This property also holds for the integer 9.
In this problem, we will investigate this property for other integers.
Input
The first line of input is an integer T (T < 100) that indicates the number of test cases. Each case is
a line containing 3 positive integers A, B and K. 1 ≤ A ≤ B < 2
31 and 0 < K < 10000.
Output
For each case, output the number of integers in the range [A, B] which is divisible by K and the sum
of its digits is also divisible by K.
Sample Input
3
1 20 1
1 20 2
1 1000 4
Sample Output
20
5
64
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define max(a, b) (a > b ? a : b)
int dp[12][122][10011];
int a, b, k, l, m;
int pw[10] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
int nat(int a)
{
int c, d;
int p = 0;
while (a)
{
c = a % 10;
a /= 10;
m = c;
p++;
}
return p;
}
void init()
{
int i, j, v, x;
dp[0][0][0] = 1;
for (i = 1; i <= l; i++)
{
for (j = 0; j < k; j++)
{
for (v = 0; v < k; v++)
{
for (x = 0; x < 10; x++)
{
dp[i][j][v] += dp[i - 1][(j - x%k + k) % k][(v - (x * pw[i - 1])%k+k) % k];
}
}
}
}
}
void cle()
{
int i, j, v, x;
dp[0][0][0] = 0;
for (i = 1; i <= l; i++)
{
for (j = 0; j < k; j++)
{
for (v = 0; v < k; v++)
{
dp[i][j][v]=0;
}
}
}
}
int solve(int a, int k1, int k2)
{
int x;
int ans = 0;
int u = nat(a);
if(u==0)
{
return 0;
}
for (x = 0; x < m; x++)
{
ans += dp[u - 1][(k1 - x%k +k) % k][(k2 - (x * pw[u - 1])%k+k) % k];
}
ans += solve(a % pw[u-1], (k1 - m % k + k) % k, (k2 - (m * pw[u-1])%k + k) % k);
return ans;
}
int main()
{
int t;
scanf("%d", &t);
for (int kcase = 1; kcase <= t; kcase++)
{
scanf("%d %d %d", &a, &b, &k);
l = max(nat(a), nat(b));
if (k>9*10)
{
printf("0\n");
continue;
}
else
{
init();
printf("%d\n", solve(b+1, 0, 0) - solve(a, 0, 0));
cle();
}
}
return 0;
}