
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 Smallest K-Digit Number Divisible by X
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.
Algorithm
minKDigit(k, x)
begin min = 10 ^ (k-1) if min is divisible by x, return min otherwise return (min + x) – ((min + x) mod x) end
Example
#include<iostream> #include<cmath> 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); }
Output
Enter Digit Count(K) and Divisor(N): 5 29 Result is: 10005
Output
Enter Digit Count(K) and Divisor(N): 6 87 Result is: 100050
Advertisements