- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 all pairs (a,b) and (c,d) in array which satisfy ab = cd in C++
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.
- for j := i + 1 to n-1, do
Example
#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)
- Related Articles
- Find all pairs (a, b) in an array such that a % b = k in C++
- Count index pairs which satisfy the given condition in C++
- Count triplet pairs (A, B, C) of points in 2-D space that satisfy the given condition in C++
- C++ program to find out the number of pairs in an array that satisfy a given condition
- Find four elements a, b, c and d in an array such that a+b = c+d in C++
- Find numbers a and b that satisfy the given condition in C++
- Count all pairs of an array which differ in K bits in C++
- Find largest d in array such that a + b + c = d in C++
- If AB||CD and CD||EF Find $angle$ACE"
- Sum of XOR of all pairs in an array in C++
- Print all pairs of anagrams in a given array of strings in C++
- Find all the pairs with given sum in a BST in C++
- Which pigment is present universally in all the green plants?(a.) Chlorophyll a(b.) Chlorophyll b(c.) Chlorophyll c(d.) Chlorophy11 d
- Find pairs in array whose sums already exist in array in C++
- Print all pairs in an unsorted array with equal sum in C++

Advertisements