# C++ Program for Largest K digit number divisible by X?

In this problem we will try to find largest K-digit number, that will be divisible by X. To do this task we will take the largest K digit number by this formula ((10^k) – 1). Then check whether the number is divisible by X or not, if not, we will get the exact number by using this formula.

𝑚𝑎𝑥−(𝑚𝑎𝑥 𝑚𝑜𝑑 𝑋)

One example is like a 5-digit number, that is divisible by 29. So the largest 5-digit number is 99999. This is not divisible by 29. Now by applying the formula we will get −

99999−(99999 𝑚𝑜𝑑 29)=99999−7=99992

The number 99992 is divisible by 29.

## Algorithm

#### maxKDigit(k, x)

begin
max = (10^k) - 1
if max is divisible by x, return max
otherwise return max – (max mod x)
end

## Example

Live Demo

#include<iostream>
#include<cmath>
using namespace std;
long max_k_digit(int k, int x){
//get the maximum number of k digits
int max = pow(10, k) - 1;
if(max % x == 0){
return max;
}
return (max) - (max % x);
}
main() {
int k, x;
cout << "Enter Digit Count(K) and Divisor(N): ";
cin >> k >> x;
cout << "Result is: " << max_k_digit(k, x);
}

## Output

Enter Digit Count(K) and Divisor(N): 5 29
Result is: 99992

## Output

Enter Digit Count(K) and Divisor(N): 6 87
Result is: 999978