Editorial for COCI '06 Contest 6 #5 V
                Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
        Submitting an official solution before solving the problem yourself is a bannable offence.
If  is larger than say 
, then 
 is at most 
, meaning that there are at most one million multiples of 
 to check. A "naive" solution that checks each and verifies that it is composed of the given digits is efficient enough.
If  is at most 
, then integers divided by 
 give remainders no larger than 
.
We will construct the function , the number of multiples of 
 between 
 and 
, if we still have to place 
 more digits (of 
) and 
 represents the digits already placed.
To calculate the values of this function, first observe that, for any  and 
, we can only form numbers between 
 and 
, inclusive. Based on this we recognise three cases:
- If all numbers are between 
and
, then the actual prefix doesn't matter when forming the rest of the number, just its remainder when divided by
. The limited range of the remainders reduces the state space and we can memoize the values of the function based on the remainder.
 - If all numbers are less than 
or greater than
, then the value is zero.
 - If some (but not all) numbers are between 
and
, then the value of the function doesn't depend only on the remainder of dividing the prefix by
, so it isn't possible to memoize the value of the function on the remainder. Luckily, there are few such cases (proportional to the length of the number).
 
Comments