Kth largest N digit number divisible by M
Last Updated :
03 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.
C++
#include <iostream>
using namespace std;
int findAnswer( int N, int K, int M)
{
int i;
long long int r = 0;
for (i = 1; i <= N; i++) {
r = r * 10 + 9;
}
long long int u = r - (r % M)
- M * (K - 1);
return u;
}
int main()
{
int N = 9;
int K = 6;
int M = 4;
cout << findAnswer(N, K, M);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int findAnswer( int N, int K, int M)
{
int i;
int r = 0 ;
for (i = 1 ; i <= N; i++) {
r = r * 10 + 9 ;
}
int u = r - (r % M)
- M * (K - 1 );
return u;
}
public static void main(String[] args)
{
int N = 9 ;
int K = 6 ;
int M = 4 ;
System.out.print(findAnswer(N, K, M));
}
}
|
Python3
def findAnswer(N, K, M):
i = None
r = 0 ;
for i in range ( 1 , N + 1 ):
r = r * 10 + 9 ;
u = r - (r % M) - M * (K - 1 );
return u;
N = 9 ;
K = 6 ;
M = 4 ;
print (findAnswer(N, K, M));
|
C#
using System;
class GFG
{
static int findAnswer( int N, int K, int M)
{
long r = 0;
for ( int i = 1; i <= N; i++) {
r = r * 10 + 9;
}
long u = r - (r % M)
- M * (K - 1);
return ( int )u;
}
public static void Main()
{
int N = 9;
int K = 6;
int M = 4;
Console.Write(findAnswer(N, K, M));
}
}
|
Javascript
<script>
function findAnswer(N, K, M) {
let i;
let r = 0;
for (i = 1; i <= N; i++) {
r = r * 10 + 9;
}
let u = r - (r % M)
- M * (K - 1);
return u;
}
let N = 9;
let K = 6;
let M = 4;
document.write(findAnswer(N, K, M));
</script>
|
Time Complexity: O(MaxDigit), Where maxDigit is the largest N digit number.
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...