Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 05 Dec, 2018

Integers X and K are given. The task is to find highest K-digit number divisible by X.

Examples:

Input : X = 30, K = 3
Output : 990
990 is the largest three digit 
number divisible by 30.

Input : X = 7, K = 2
Output : 98

An efficient solution is to use below formula.

ans = MAX - (MAX % X)
where MAX is the largest K digit 
number which is  999...K-times

The formula works on simple school method division. We remove remainder to get the largest divisible number.




// CPP code to find highest K-digit number divisible by X
#include <bits/stdc++.h>
using namespace std;
  
// Function to compute the result
int answer(int X, int K)
{
    // Computing MAX
    int MAX = pow(10, K) - 1;
  
    // returning ans
    return (MAX - (MAX % X));
}
  
// Driver
int main()
{
    // Number whose divisible is to be found
    int X = 30;
  
    // Max K-digit divisible is to be found
    int K = 3;
  
    cout << answer(X, K);
}
Output:
990

Please refer complete article on Largest K digit number divisible by X for more details!

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :