VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kth-largest-n-digit-number-divisible-by-m/

⇱ Kth largest N digit number divisible by M - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kth largest N digit number divisible by M

Last Updated : 3 Feb, 2022

Given three positive integers N, K, and M. The task is to find Kth largest N digit number divisible by M

Note: K will be such an integer that Kth largest N digit number divisible by M always exists.

Examples

Input: N = 2, K = 2, M = 2
Output: 96
Explanation: The 2nd largest 2 digit number divisible by 2 is 96. 

Input: N = 9, K = 6, M = 4
Output: 999999976

Approach: The problem is maths-based. Given three numbers N, K, and M. It is required to find the Kth largest N digit number divisible by M. To get the largest N digit divisible by M, at first it is required to find the largest N digit number(say P), which is N times 9
Now the largest N digit number divisible by M is (P - (P%M)).
Therefore, subtract (K-1) times M from this value to get the Kth largest value of N digit number which is divisible by M.
Given below is the conditions and mathematical expression to get Kth largest N digit number divisible by M.

Let P be the largest N digit number
Then the largest N digit number divisible by M is: (P - (P % M))
Now the Kth largest N digit number divisible by M is: [(P - (P % M)) - ((K - 1) * M)]

Below is the code according to the above formula.

 
 


Output
999999976


 

Time Complexity: O(MaxDigit), Where maxDigit is the largest N digit number.
Auxiliary Space: O(1)


 

Comment