[Math] Number of ways to make n digit number

combinatoricspermutations

Given M digits which are between 1 to 9,
Find the number of ways to form N digit number, by repeating one or more given digits such that each of M digits are present in N digit number at least once.
Example if M = 3 and N = 4
Answer is 36.

Explanation – let the three digits be 1 2 3
our N = 4, digit number can be 1123, 3211, 1132, ….. repeating 1
similarly repeating 2 and three we will get the total ans.

Since answer is large find the ans % 10000000007.
1 ≤ M ≤ N ≤ 100.

Best Answer

If I understand this correctly it is a familiar problem, equivalent to the problem of counting the number of $N$-letter words from an alphabet of size $M$, with the restriction that each letter is used at least once.

The well-known answer is $M!S(N,M)$, where $S(N,M)$ is the Stirling number of the second kind, counting the number of ways to partition $[N]$ in $M$ parts. You can find references about these Stirling numbers like recursive formulas and generating functions all over the place if you actually need to write a program that produces the answer for concrete values of $M$ and $N$.

Btw, a Java implementation using a simple summation for these Stirling numbers calculates e.g. $S(200,100)$ in a fraction of a second (although it has over 200 digits), so performance cannot be a problem for the values you mention.