Editorial for COI '07 #4 Umnožak
Submitting an official solution before solving the problem yourself is a bannable offence.
The first observation we can make is that, for all positive integers , the digit-product is always less than or equal to . From we can deduce that .
Because is a product of digits, its prime factors can only be , , and . The number of different integers with only , , and in their prime factorization that are less than or equal to is quite small (exactly ).
Since there are relatively few such values, we can iterate through all of them. Now, it suffices to solve the following problem for each fixed product :
Let . How many numbers between and have product of digits equal to ?
We can count all such numbers by considering them digit by digit from left to right using a recursive algorithm.
Let rec( string prefix, int N, int prod )
be such a recursive algorithm. The algorithm returns the total number of integers that start with prefix and have more digits whose product is prod. Its arguments are:
prefix
is the part of the number generated so farN
is the number of digits that still needs to be generated andprod
is the target digit-product of the yet to be generated part of the number.
rec( string prefix, int N, int prod )
Let max be a number we get when we append prefix with N nine digits
Let min be a number we get when we append prefix with N zero digits
If max < ceil(A/P) or min > floor(B/P) then Return 0
If N = 0 then
If prod = 1 then Return 1
else Return 0
Count = 0
For each digit D from 1 to 9
If D divides prod then
Count = Count+rec( prefix appended by digit D, N-1, prod/D )
Return Count
To speed things up, we will add memoization to the algorithm described above. In order to memorize the return values of the function efficiently, we consider two cases:
If and hold (i.e. all possible values that can be generated from this moment on are within the bounds), then the result is the same no matter the value of the number we generated so far. Therefore, we can ignore the prefix parameter.
We are left with only
N
andprod
as state parameters, and sinceN
can take on only different values andprod
only different values, we can store the result in a table and use it whenever we encounter the same parameters again.- If one of the statements and is false then the string prefix is either a prefix of or a prefix of , and the number of additional states we have to memorize is linear in (the number of digits).
Total time complexity of the algorithm is where is the number of different integers with only , , and in their prime factorization that are less than or equal to . For , we have and .
Comments