Count pairs whose products exist in array - GeeksforGeeks
Given an array, count those pair whose product value is present in array.
Read full article from Count pairs whose products exist in array - GeeksforGeeks
Given an array, count those pair whose product value is present in array.
int
countPairs(
int
arr[] ,
int
n)
{
int
result = 0;
// Create an empty hash-set that store all array element
set<
int
> Hash;
// Insert all array element into set
for
(
int
i = 0 ; i < n; i++)
Hash.insert(arr[i]);
// Generate all pairs and check is exist in 'Hash' or not
for
(
int
i = 0 ; i < n; i++)
{
for
(
int
j = i + 1; j<n ; j++)
{
int
product = arr[i]*arr[j];
// if product exists in set then we increment
// count by 1
if
(Hash.find(product) != Hash.end())
result++;
}
}
// return count of pairs whose product exist in array
return
result;
}