Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements