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
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:
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Find the count of numbers that can be formed using digits 3, 4 only and having length at max N.
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Maximize the given number by replacing a segment of digits with the alternate digits given
- Minimum number of digits to be removed so that no two consecutive digits are same
- Count numbers with same first and last digits
- Compute sum of digits in all numbers from 1 to n
- Print numbers with digits 0 and 1 only such that their sum is N
- Find the Largest number with given number of digits and sum of digits
- Count of numbers from range [L, R] whose sum of digits is Y
- Numbers having Unique (or Distinct) digits
- Check if two numbers have same number of digits
- Print all numbers less than N with at-most 2 unique digits
- Number of digits in the product of two numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.