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.

 Live Demo

#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.

Updated on: 01-Feb-2021

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements