The Wayback Machine - https://web.archive.org/web/20221023054516/https://www.geeksforgeeks.org/maximum-multiple-of-a-number-with-all-digits-same/
Skip to content
Related Articles

Related Articles

Maximum multiple of a number with all digits same

View Discussion
Improve Article
Save Article
  • Last Updated : 14 Oct, 2022
View Discussion
Improve Article
Save Article

Given two positive integers X and Y (1 ≤ Y ≤ 105), find the maximum positive multiple (say M) of X such that M is less than 10Y and all the digits in the decimal representation of M are equal.

Note: If no positive multiple exists that satisfies the conditions, return -1.

Examples:

Input: X = 1, Y = 6
Output: 999999
Explanation: 999999 is the largest integer which is a multiple of 1, has all the same digits and less than 106.

Input: X = 12, Y = 7
Output: 888888
Explanation: 888888 is the largest multiple of 12 which have all digits same and is less than 107.

Input: X = 25, Y = 10
Output: -1
Explanation: No positive integers M satisfy the conditions.

Approach: To solve the problem follow the below idea:

The main idea is to consider all the numbers less than 10Y which have the same digits in decimal representation and check if the number is a multiple of X, from all such multiples, the maximum one as the result.

Follow the steps to solve the problem:

  • Consider a function f(n, d) which denotes the remainder of the number with length n and all digits d when divided by X.
  • Calculate f(n, d) for every {n, d}.
  • Notice that f(n − 1, d) is a prefix of f(n, d). So: f(n, d) = (f(n−1, d)*10 + d)%X
  • Find the maximum value of n for which f(n, d) = 0. 
    • Choose the one with the maximum d among the ones with the maximum n.

Below is the implementation of the above approach.

C++




// C++ program for finding maximum multiple
// of a number with all the digits same
  
#include <bits/stdc++.h>
using namespace std;
  
// Function for calculating maximum
// multiple of X less than 10^Y
string maxMultiple(int X, int Y)
{
    // f(n, d) -> d digit is repeated
    // n times (ddd....d)
    pair<int, int> res = { 0, 0 };
    int number = 0;
    for (int d = 1; d <= 9; ++d) {
        for (int n = 1; n <= Y; ++n) {
            number = (10 * number + d) % X;
            if (number == 0)
                res = max(res, { n, d });
        }
    }
  
    // No such multiple exits so return -1
    if (res.first == 0)
        return "-1";
  
    // Generating the multiple
    // from pair res
    string ans = "";
    for (int i = 1; i <= res.first; i++)
        ans += (res.second + '0');
  
    return ans;
}
  
// Driver function
int main()
{
    int X = 12, Y = 7;
  
    // Function Call
    cout << maxMultiple(X, Y);
  
    return 0;
}

Output

8888888

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!