C++ Program for Smallest K digit number divisible by X?

C++Server Side ProgrammingProgramming

In this problem we will try to find smallest K-digit number, that will be divisible by X. To do this task we will take the smallest 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.

(min+ 𝑋)−((min+ 𝑋) 𝑚𝑜𝑑 𝑋)

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

(10000+ 29)−((10000+29) 𝑚𝑜𝑑 29)=10029−24=10005

The number 10005 is divisible by 29.


minKDigit(k, x)

   min = 10 ^ (k-1)
   if min is divisible by x, return min
   otherwise return (min + x) – ((min + x) mod x)


 Live Demo

using namespace std;
long min_k_digit(int k, int x) {
   //get the minimum number of k digits
   int min = pow(10, k-1);
   if(min % x == 0) {
      return min;
   return (min + x) - ((min + x) % x);
main() {
   int k, x;
   cout << "Enter Digit Count(K) and Divisor(N): ";
   cin >> k >> x;
   cout << "Result is: " << min_k_digit(k, x);


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


Enter Digit Count(K) and Divisor(N): 6 87
Result is: 100050
Published on 24-Jul-2019 13:00:48