Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Largest N digit number divisible by given three numbers in C++
In this tutorial, we are going to write a program that finds the largest n-digit number that is divisible by the given three numbers.
Let's see the steps to solve the problem.
- Initialise three numbers along with n.
- Find the LCM of three numbers.
- Store the largest number with n-digits.
- If the largest number is divisible by n, then return it.
- Else check for the number obtained from subtracting remainder in the above step.
Example
Let's see the code.
#include <bits/stdc++.h>
using namespace std;
int LCM(int x, int y, int z) {
int ans = ((x * y) / (__gcd(x, y)));
return ((z * ans) / (__gcd(ans, z)));
}
int findNumber(int n, int x, int y, int z) {
int lcm = LCM(x, y, z);
int largestNDigitNumber = pow(10, n) - 1;
int remainder = largestNDigitNumber % lcm;
if (remainder == 0) {
return largestNDigitNumber;
}
largestNDigitNumber -= remainder;
if (largestNDigitNumber >= pow(10, n - 1)) {
return largestNDigitNumber;
}
return 0;
}
int main() {
int n = 4, x = 6, y = 7, z = 8;
int result = findNumber(n, x, y, z);
if (result != 0) {
cout << result << endl;
}else {
cout << "Not possible" << endl;
}
return 0;
}
Output
If you run the above code, then you will get the following result.
9912
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements
