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
Find A and B from list of divisors in C++
In this tutorial, we are going to solve the below problem.
Given an array of integers, we have to find two numbers A and B. All the remaining numbers in the array are the divisors of A and B.
If a number is a divisor of both A and B, then it will present twice in the array.
Let's see the steps to solve the problem.
The max number in the array is one of the numbers from A and B. Let's say it is A.
Now, B will be the second-largest number or the number which is not a divisor of A.
Example
Let's see the code.
#include <bits/stdc++.h>
using namespace std;
void findTheDivisors(int arr[], int n) {
sort(arr, arr + n);
int A = arr[n - 1], B = -1;
for (int i = n - 2; i > -1; i--) {
if (A % arr[i] != 0) {
B = arr[i];
break;
}
if (i - 1 >= 0 && arr[i] == arr[i - 1]) {
B = arr[i];
break;
}
}
cout << "A = " << A << ", B = " << B << endl;
}
int main() {
int arr[] = { 3, 2, 3, 4, 12, 6, 1, 1, 2, 6 };
findTheDivisors(arr, 10);
return 0;
}
Output
If you execute the above program, then you will get the following result.
A = 12, B = 6
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements