Given a number N, find the minimum possible sum of digits that can be obtained from a positive Multiple of N.
Constraints : 1<=N<=10^5.
Input : N = 6 Output : 3 Explanation: 6*2 = 12, sum of digits is 1+2 = 3. Input : N = 20 Output : 1 20*5 = 100, sum of digits is 1+0+0=1
Approach : The problem is totally based on observation. For N = 6, the answer is 12.
So we can write 12 as : 1-(*10)–>10–(+1)–>11–(+1)–>12. What the sequence describes is we can write any number >=1, as the sum’s of +1 and product of *10’s, starting with 1.
Another observation is, when we add +1 to the digit, the digit sum increases by +1, unless the last digit is 9.
The second observation is, when we multiply the digit by 10, sum of digits remains constant.
Now, since we want a multiple of N, so any multiple of N % N will be 0.
So, taking the above analysis, we can build a graph of K vertices, for any vertex X, the weight of node from X to X+1 will be one, and weight of node from X to (X*10)%N will be 0. We took modulo N since the vertex lies within 0 to N-1.
The answer will be the shortest distance from 1 to 0, because of (Any multiple of N) mod N = 0.
We can use Dijkstra’s theorem to find the shortest distance between 1 and 0. Let it be d. Answer will be 1+d, as we have also to consider edge 0 to 1.
The time complexity of this solution will be O(E+VLogV) = O(N+NLogN) = O(NlogN) as we will travel at most N vertices and Edges.
One more thing to note is, since, after xyz..9, the next digit will be abc..0, but it will not affect our answer.
Proof: lets take example of N = 11, answer is 2. It is from 11*1 = 11 and 11*10 = 110.
Since 110 is a 10’s multiple of N and also an answer, either we have already hit the answer because if 110 is some 10’s multiple of N, then there must exist a number less than this with no leading 0’s in our answer, that is 11.
So either we will surpass 10’s multiple of N, if it is not an answer, or we will have already hit the answer before if some 10’s multiple of N is in answer.
Below is the implementation of the above approach:
Minimum possible sum of digits is 2
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.