
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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.
- Related Articles
- Find number from its divisors in C++
- Find sum of divisors of all the divisors of a natural number in C++
- Find all divisors of a natural number in java
- Count total divisors of A or B in a given range in C++
- Find all divisors of a natural number - Set 1 in C++
- Find all divisors of a natural number - Set 2 in C++
- Find Itinerary from a given list of tickets in C++
- Divisors of factorials of a number in java
- Find largest sum of digits in all divisors of n in C++
- Divisors of n-square that are not divisors of n in C++ Program
- Find a list of invalid email address from a table in MySQL?
- Program to find folded list from a given linked list in Python
- Find numbers with K odd divisors in a given range in C++
- Find all close matches of input string from a list in Python
- Program to find H-Index from a list of citations in C++

Advertisements