Friday, July 30, 2021

Published July 30, 2021 by Anonymous with 0 comment

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.

Examples:

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:

C++

#include <bits/stdc++.h>

using namespace std;

  

int smallest(int k, int d)

{

    int cnt = 1;

    int m = d % k;

  

    

    

    vector<int> v(k, 0);

    v[m] = 1;

  

    

    while (1) {

        if (m == 0)

            return cnt;

        m = (((m * (10 % k)) % k) + (d % k)) % k;

  

        

        

        if (v[m] == 1)

            return -1;

        v[m] = 1;

        cnt++;

    }

    return -1;

}

  

int main()

{

  

    int d = 1;

    int k = 41;

    cout << smallest(k, d);

    return 0;

}

Time Complexity : O(K)
Auxiliary Space : O(K)

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.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


Adblock test (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment