Most a number of of a quantity with all digits identical

[ad_1]

View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given two optimistic integers X and Y (1 ≤ Y ≤ 105), discover the utmost optimistic a number of (say M) of X such that M is lower than 10Y and all of the digits within the decimal illustration of M are equal.

Word: If no optimistic a number of exists that satisfies the situations, return -1.

Examples:

Enter: X = 1, Y = 6
Output: 999999
Clarification: 999999 is the biggest integer which is a a number of of 1, has all the identical digits and fewer than 106.

Enter: X = 12, Y = 7
Output: 888888
Clarification: 888888 is the biggest a number of of 12 which have all digits identical and is lower than 107.

Enter: X = 25, Y = 10
Output: -1
Clarification: No optimistic integers M fulfill the situations.

Strategy: To unravel the issue observe the under thought:

The primary thought is to think about all of the numbers lower than 10Y which have the identical digits in decimal illustration and test if the quantity is a a number of of X, from all such multiples, the utmost one because the outcome.

Comply with the steps to resolve the issue:

  • Contemplate a perform f(n, d) which denotes the rest of the quantity with size n and all digits d when divided by X.
  • Calculate f(n, d) for each {n, d}.
  • Discover that f(n − 1, d) is a prefix of f(n, d). So: f(n, d) = (f(n−1, d)*10 + d)%X
  • Discover the utmost worth of n for which f(n, d) = 0. 
    • Select the one with the utmost d among the many ones with the utmost n.

Under is the implementation of the above method.

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

string maxMultiple(int X, int Y)

{

    

    

    pair<int, int> res = { 0, 0 };

    int quantity = 0;

    for (int d = 1; d <= 9; ++d) {

        for (int n = 1; n <= Y; ++n) {

            quantity = (10 * quantity + d) % X;

            if (quantity == 0)

                res = max(res, { n, d });

        }

    }

  

    

    if (res.first == 0)

        return "-1";

  

    

    

    string ans = "";

    for (int i = 1; i <= res.first; i++)

        ans += (res.second + '0');

  

    return ans;

}

  

int important()

{

    int X = 12, Y = 7;

  

    

    cout << maxMultiple(X, Y);

  

    return 0;

}

Time Complexity: O(Y)
Auxiliary Area: O(1)

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *