This is not an easy problem!. But you come to realize that this is one giant conditional statement.
There are 9 possible values each of p0, p1, and q. For each combination of p0, p1, and q, identify how n determines if the generated number is divisible by q. For example:
- If p0 = 1, p1 = 1, and q = 2, then no matter the size of n, the generated number is not divisible by 2. (The generated numbers are 1, 11, 111, 1111, etc.)
- If p0 = 1, p1 = 2, and q = 2, then the generated number is divisible by 2 when n mod 2 is equal to 0. (The generated numbers are 1, 12, 121, 1212, etc.)
I wrote a great deal of code to determine the patterns. The case where q = 7 was particularly difficult.
Then I wrote a test suite that iterated over all values of p0, p1, and q, and values of n in the range appropriate for the problem. This allowed me to validate all possible combinations were correct.