Count pairs whose products exist in array | A hashing based Java 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
import java . util . * ; class GFG { static int countPairs ( int arr [ ] , int n ) { int result = 0 ; HashSet < Integer > Hash = new HashSet < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Hash . add ( 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 . contains ( product ) ) { result ++ ; } } } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 2 , 4 , 12 , 5 , 3 } ; int n = arr . length ; System . out . println ( countPairs ( arr , n ) ) ; } }