Editorial
First, let us characterize all positive integers satisfying the condition.
Every one-digit positive integer satisfies the condition. Indeed, and are different one-digit numbers, or when , so their LCS length is .
Now suppose has at least two digits. If the last digit of is not , then is obtained by decreasing only the last digit of by . Therefore, the prefix before the last digit remains unchanged, and this prefix is nonempty. Hence and have a common digit, so their LCS length cannot be .
Thus, any valid with at least two digits must end with . Remove as many trailing zeros as possible and write
where does not end with .
If has at least two digits, then is obtained by decreasing only the last digit of by , so a nonempty prefix remains unchanged. Therefore, and still have a common digit. Hence must be a one-digit number.
So every valid number with at least two digits must have the form
Here, and .
If , then the decimal representation of contains digit , and the suffix of contains digit , so they have a common digit. Therefore, is impossible. Conversely, if , the digits of are only and , while the digits of are only and . These sets are disjoint, so the condition is satisfied.
Therefore, the valid numbers are listed as follows.
If , the answer is simply .
If , then
where
and
Since can be very large, we process it as a decimal string. To compute , it is enough to compute . To compute , subtract from the decimal string and divide it by , keeping only the quotient modulo .
Finally, by Fermat's little theorem,
Therefore, when computing , it is enough to know modulo .
The time complexity is , and the memory usage is .