Given two integers N and K, the task is to calculate the number of integers in the range [0, N] whose digit sum is a multiple of K. The answer could be large, so print the answer modulo 109 +7.
Input: N = 10, K = 5
0 and 5 are the only possible integers.
Input: N = 30, K = 4
Naive Approach: For small value of N, loop through the range [0, N] and check if the sum of the digits of the numbers are multiples of K or not.
Efficient Approach: The idea is to use digit dp to solve this problem. Subproblems iterating through all index value from left or most significant digit(MSD) in the given integer will be solved and for each index, store the number of ways such that (sum of digits upto current index) mod K to be zero. The dp states will be:
idx = position, it tells about the index value from left in the given integer
sum = sum of digits mod k, This parameter will store the (sum of digits mod k) in the generated integer from most significant digit(MSD) to p
tight = flag if the current value is crossing the range (1, n) or not
For unrestricted range tight = 0
For restricted range tight = 1
Let’s say we are at the MSD having index idx. So initially the sum will be 0. At every position, set a limit that is always in the range [0, 9].
Therefore, fill the digit at index by the digits in its range from 0 to limit and fetch the answer from the next state having index = idx + 1 and new_tight for next state is calculated separately. The dp state definition will be:
dp[idx][sum][tight] += dp[idx + 1][(sum + d) % k][new_tight]
for d in [0, limit]
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.