VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-multiple-of-a-number-with-all-digits-same/

⇱ Maximum multiple of a number with all digits same - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum multiple of a number with all digits same

Last Updated : 7 Mar, 2024

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.

Step-by-step approach:

  • 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.


Output
888888

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

Comment
Article Tags: