Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
Given three positive integers N, A and B. The task is to count the numbers of length N containing only digits A and B and whose sum of digits also contains the digits A and B only. Print the answer modulo 109 + 7.
Input: N = 3, A = 1, B = 3
Possible numbers of length 3 are 113, 131, 111, 333, 311, 331 and so on…
But only 111 is a valid number since its sum of digits is 3 (contains digits A and B only)
Input: N = 10, A = 2, B = 3
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Approach: The idea is to express the sum of digits of the number as a linear equation in two variables i.e.
S = X * A + Y * B where A and B are the given digits and X and Y are the frequencies of these digits respectively.
Since, the sum of (X + Y) should be equal to N (length of the number) according to the given condition, we can replace Y with (N – X) and the equation reduces to S = X * A + (N – X) * B. Thus, X = (S – N * B) / (A – B).
Now, we can iterate over all possible values of S where minimum value of S is an N-digit number where all digits are 1 and maximum value of S is an N-digit number where all digits are 9 and check if the current value contains only digits A and B. Find the values of X and Y using the above formula for valid current S. Since, we can also permute the digits count of numbers will be (N! / X! Y!) for current value S. Add this result to the final answer.
Note: Use Fermat Little Theorem to compute n! % p.
Below is the implementation of the above approach: