# Find all pairs (a,b) and (c,d) in array which satisfy ab = cd in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A, from that array, we have to choose two pairs (a, b) and (c, d), such that ab = cd. Let the array A = [3, 4, 7, 1, 2, 9, 8]. The output pairs are (4, 2) and (1, 8). To solve this, we will follow these steps −

• For i := 0 to n-1, do
• for j := i + 1 to n-1, do
• get product = arr[i] * arr[j]
• if product is not present in the hash table, then Hash[product] := (i, j)
• if product is present in the hash table, then print previous and current elements.

## Example

Live Demo

#include <iostream>
#include <unordered_map>
using namespace std;
void displayPairs(int arr[], int n) {
bool found = false;
unordered_map<int, pair < int, int > > Hash;
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
int prod = arr[i]*arr[j];
if (Hash.find(prod) == Hash.end())
Hash[prod] = make_pair(i,j);
else{
pair<int,int> pp = Hash[prod];
cout << "(" << arr[pp.first] << ", " << arr[pp.second] << ") and (" << arr[i]<<", "<<arr[j] << ")"<<endl; found = true;
}
}
}
if (found == false)
cout << "No pairs have Found" << endl;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = sizeof(arr)/sizeof(int);
displayPairs(arr, n);
}

## Output

(1, 6) and (2, 3)
(1, 8) and (2, 4)
(2, 6) and (3, 4)
(3, 8) and (4, 6)