Count pairs whose products exist in array | A hashing based C ++ program to count pairs whose product exists in arr [ ] ; Returns count of pairs whose product exists in arr [ ] ; Create an empty hash - set that store all array element ; Insert all array element into set ; Generate all pairs and check is exist in ' Hash ' or not ; if product exists in set then we increment count by 1 ; return count of pairs whose product exist in array ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int result = 0 ; set < int > Hash ; for ( int i = 0 ; i < n ; i ++ ) Hash . insert ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int product = arr [ i ] * arr [ j ] ; if ( Hash . find ( product ) != Hash . end ( ) ) result ++ ; } } return result ; } int main ( ) { int arr [ ] = { 6 , 2 , 4 , 12 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }