Smallest length of number divisible by K formed by using D only
Given 2 integers D and K, the task is to find the minimum length of a number formed by repeating D that will be divisible by K. If no such number exists, print -1.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : D = 1, K = 37
Output : 3
Explanation : The minimum number formed by repeating 1 that is divisible by 37 is 111
Input : D = 2, K = 36
Output : -1
Naive Approach : The idea is to keep forming the number until it becomes divisible by K or it exceeds the range.
Time Complexity : O(10^18)
Auxiliary Space : O(1)
Efficient Approach : The idea is to store the remainders that are produced by dividing the number with K and storing the remainders in an array. And when the same remainder appears again, it can be concluded that no such number exists. Follow the steps below to solve the problem:
- Initialize the variables cnt as 0 to store the answer and m to store the number.
- Initialize the vector v of size K to store the remainders and set the value of v[m] as 1.
- Iterate in a while loop and perform the following steps
- If m is equal to 0, then return the value of cnt as the answer.
- Set the value of m as (((m * (10 % k)) % k) + (d % k)) % k.
- If v[m] is equal to 1, then return -1 as no such number is possible.
- Set the value of v[m] as 1 and increase the value of cnt by 1.
- After performing the above steps, return the value of -1.
Below is the implementation of the above approach:
Time Complexity : O(K)
Auxiliary Space : O(K)