Count all distinct pairs with product equal to K

Given an integer array arr[] of size N and a positive integer K, the task is to count all the distinct pairs in the array with product equal to K.

Examples:

Input: arr[] = {1, 5, 3, 4, 2}, K = 3
Output: 1
Explanation:
There is only one pair (1, 3) with product = K = 3.



Input: arr[] = {1, 2, 16, 4, 4}, K = 16
Output: 2
Explanation:
There are two pairs (1, 16) and (4, 4) with product = K = 16.

Naive Approach: The naive approach for this problem is to consider all pairs one by one and check the product between every pair. If the product is equal to K, then increment the count and finally print it. However, the limitation is that this approach doesn’t work if there are duplicates in the array because we only need to consider distinct pairs.

Below is the implementation of the above approach:

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count the number of pairs
// whose product is equal to K
  
#include <iostream>
using namespace std;
  
// Function to count the number of pairs
// whose product is equal to K
int countPairsWithProdK(int arr[], int n, int k)
{
    int count = 0;
  
    // Pick all elements one by one
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++)
  
            // Check if the product of this pair
            // is equal to K
            if (arr[i] * arr[j] == k)
                count++;
    }
  
    return count;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 5, 3, 4, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
  
    cout << countPairsWithProdK(arr, N, K);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count the number of pairs
// whose product is equal to K
class GFG {
  
     // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProdK(int arr[], int n, int k)
    {
        int count = 0;
      
        // Pick all elements one by one
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++)
      
                // Check if the product of this pair
                // is equal to K
                if (arr[i] * arr[j] == k)
                    count++;
        }
      
        return count;
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        int arr[] = { 1, 5, 3, 4, 2 };
        int N = arr.length;
        int K = 3;
      
        System.out.println(countPairsWithProdK(arr, N, K));
    }
}
  
// This code is contributed by AnkitRai01

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count the number of pairs
# whose product is equal to K
  
# Function to count the number of pairs
# whose product is equal to K
def countPairsWithProdK(arr, n, k):
    count = 0
  
    # Pick all elements one by one
    for i in range(n):
        for j in range(i + 1, n):
  
            # Check if the product of this pair
            # is equal to K
            if (arr[i] * arr[j] == k):
                count += 1
  
    return count
  
# Driver code
arr = [1, 5, 3, 4, 2]
N = len(arr)
K = 3
  
print(countPairsWithProdK(arr, N, K))
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count the number of pairs
// whose product is equal to K
using System;
  
class GFG {
  
     // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProdK(int []arr, int n, int k)
    {
        int count = 0;
      
        // Pick all elements one by one
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++)
      
                // Check if the product of this pair
                // is equal to K
                if (arr[i] * arr[j] == k)
                    count++;
        }
      
        return count;
    }
      
    // Driver code
    public static void Main (string[] args) 
    {
        int []arr = { 1, 5, 3, 4, 2 };
        int N = arr.Length;
        int K = 3;
      
        Console.WriteLine(countPairsWithProdK(arr, N, K));
    }
}
  
// This code is contributed by AnkitRai01

chevron_right


Output:

1

Time Complexity: O(N2)

Efficient Approach: The idea is to use hashing.

  1. Initially, insert all the elements from the array into the hashmap. While inserting, ignore if a particular element is already present in the hashmap.
  2. Now, we have all the unique elements in the hash. So, for every element in the array arr[i], we check if arr[i] / K is present in the hashmap or not.
  3. If the value is present, then we increment the count and remove that particular element from the hash( To get the unique pairs).

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count the number of pairs
// whose product is equal to K
  
#include <algorithm>
#include <iostream>
using namespace std;
#define MAX 100000
  
// Function to count the number of pairs
// whose product is equal to K
int countPairsWithProductK(int arr[], int n, int k)
{
    // Initialize the count
    int count = 0;
  
    // Initialize empty hashmap.
    bool hashmap[MAX] = { false };
  
    // Insert array elements to hashmap
    for (int i = 0; i < n; i++)
        hashmap[arr[i]] = true;
  
    for (int i = 0; i < n; i++) {
        int x = arr[i];
  
        double index = 1.0 * k / arr[i];
  
        // Checking if the index is a whole number
        // and present in the hashmap
        if (index >= 0
            && ((index - (int)(index)) == 0)
            && hashmap[k / x])
  
            count++;
        hashmap[x] = false;
    }
    return count;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 5, 3, 4, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
  
    cout << countPairsWithProductK(arr, N, K);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count the number of pairs
// whose product is equal to K
      
class GFG
{
    static int MAX = 100000;
      
    // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProductK(int arr[], int n, int k)
    {
        // Initialize the count
        int count = 0;
        int i;
  
        // Initialize empty hashmap.
        boolean hashmap[] = new boolean[MAX];
          
        // Insert array elements to hashmap
        for (i = 0; i < n; i++)
            hashmap[arr[i]] = true;
          
        for (i = 0; i < n; i++) {
            int x = arr[i];
          
            double index = 1.0 * k / arr[i];
          
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - (int)(index)) == 0)
                && hashmap[k / x])
          
                count++;
            hashmap[x] = false;
        }
        return count;
    }
      
    // Driver code
    public static void main(String []args)
    {
        int arr[] = { 1, 5, 3, 4, 2 };
        int N = arr.length;
        int K = 3;
          
        System.out.print(countPairsWithProductK(arr, N, K));
          
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count the number of pairs
# whose product is equal to K
MAX = 100000;
  
# Function to count the number of pairs
# whose product is equal to K
def countPairsWithProductK(arr, n, k) :
  
    # Initialize the count
    count = 0;
  
    # Initialize empty hashmap.
    hashmap = [False]*MAX ;
  
    # Insert array elements to hashmap
    for i in range(n) :
        hashmap[arr[i]] = True;
  
    for i in range(n) :
        x = arr[i];
  
        index = 1.0 * k / arr[i];
  
        # Checking if the index is a whole number
        # and present in the hashmap
        if (index >= 0
            and ((index - int(index)) == 0)
            and hashmap[k // x]) :
  
                count += 1;
          
        hashmap[x] = False;
      
    return count;
  
# Driver code
if __name__ == "__main__" :
    arr = [ 1, 5, 3, 4, 2 ];
    N = len(arr);
    K = 3;
  
    print(countPairsWithProductK(arr, N, K));
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count the number of pairs
// whose product is equal to K     
using System;
  
class GFG
{
    static int MAX = 100000;
       
    // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProductK(int []arr, int n, int k)
    {
        // Initialize the count
        int count = 0;
        int i;
   
        // Initialize empty hashmap.
        bool []hashmap = new bool[MAX];
           
        // Insert array elements to hashmap
        for (i = 0; i < n; i++)
            hashmap[arr[i]] = true;
           
        for (i = 0; i < n; i++) {
            int x = arr[i];
           
            double index = 1.0 * k / arr[i];
           
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - (int)(index)) == 0)
                && hashmap[k / x])
           
                count++;
            hashmap[x] = false;
        }
        return count;
    }
       
    // Driver code
    public static void Main(String []args)
    {
        int []arr = { 1, 5, 3, 4, 2 };
        int N = arr.Length;
        int K = 3;
           
        Console.Write(countPairsWithProductK(arr, N, K));         
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

1

Time Complexity: O(N * log(N))

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.