Pair with given product | Set 1 ( Find if any pair exists ) | C ++ program to find if there is a pair with given product . ; Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; Create an empty set and insert first element into it ; Traverse remaining elements ; 0 case must be handles explicitly as x % 0 is undefined behaviour in C ++ ; x / arr [ i ] exists in hash , then we found a pair ; Insert arr [ i ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isProduct ( int arr [ ] , int n , int x ) { if ( n < 2 ) return false ; unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { if ( x == 0 ) return true ; else continue ; } if ( x % arr [ i ] == 0 ) { if ( s . find ( x / arr [ i ] ) != s . end ( ) ) return true ; s . insert ( arr [ i ] ) ; } } return false ; } int main ( ) { int arr [ ] = { 10 , 20 , 9 , 40 } ; int x = 400 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isProduct ( arr , n , x ) ? cout << " Yes STRNEWLINE " : cout << " Non " ; x = 190 ; isProduct ( arr , n , x ) ? cout << " Yes STRNEWLINE " : cout << " Non " ; return 0 ; }