Count all possible pairs in given Array with product K - GeeksforGeeks

28 Feb, 2022
Given an integer array arr[] of size N and a positive integer K, the task is to count all the pairs in the array with a product equal to K.
Examples:
Input: arr[] = {1, 2, 16, 4, 4, 4, 8 }, K=16Output: 5Explanation: Possible pairs are (1, 16), (2, 8), (4, 4), (4, 4), (4, 4)
Input: arr[] = {1, 10, 20, 10, 4, 5, 5, 2 }, K=20Output: 5Explanation: Possible pairs are (1, 20), (2, 10), (2, 10), (4, 5), (4, 5)
Approach: The idea is to use hashing to store the elements and check if K/arr[i] exists in the array or not using the map and increase the count accordingly. 
Follow the steps below to solve the problem:
Initialize the variable count as 0 to store the answer.
Initialize the unordered_map<int, int> mp[].
Iterate over the range [0, N) using the variable i and store the frequencies of all elements of the array arr[] in the map mp[].
Iterate over the range [0, N) using the variable i and perform the following tasks:Initialize the variable index as K/arr[i].If K is not a power of 2 and index is present in map mp[] then increase the value of count by mp[arr[i]]*mp[index] and erase both of them from the map mp[].If K is a power of 2 and index is present in map mp[] then increase the value of count by mp[index]*(mp[index]-1)/2 and erase it from the map mp[].
Initialize the variable index as K/arr[i].
If K is not a power of 2 and index is present in map mp[] then increase the value of count by mp[arr[i]]*mp[index] and erase both of them from the map mp[].
If K is a power of 2 and index is present in map mp[] then increase the value of count by mp[index]*(mp[index]-1)/2 and erase it from the map mp[].
After performing the above steps, print the value of count as the answer.
Below is the implementation of the above approach.
C++14
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count// the total number of pairsint countPairsWithProductK(    int arr[], int n, int k) {     int count = 0;     // Initialize hashmap.    unordered_map<int, int> mp;     // Insert array elements to hashmap    for (int i = 0; i < n; i++) {         mp[arr[i]]++;    }     for (int i = 0; i < n; i++) {         double index = 1.0 * k / arr[i];         // If k is not power of two        if (index >= 0            && ((index - (int)(index)) == 0)            && mp.find(k / arr[i]) != mp.end()            && (index != arr[i])) {             count += mp[arr[i]] * mp[index];             // After counting erase the element            mp.erase(arr[i]);             mp.erase(index);        }         // If k is power of 2        if (index >= 0            && ((index - (int)(index)) == 0)            && mp.find(k / arr[i]) != mp.end()            && (index == arr[i])) {             // Pair count            count += (mp[arr[i]]                      * (mp[arr[i]] - 1))                     / 2;             // After counting erase the element;            mp.erase(arr[i]);        }    }     return count;} // Driver Codeint main() {     int arr[] = { 1, 2, 16, 4, 4, 4, 8 };     int N = sizeof(arr) / sizeof(arr[0]);     int K = 16;     cout << countPairsWithProductK(arr, N, K);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{   // Function to count  // the total number of pairs  static int countPairsWithProductK(    int arr[], int n, int k)   {     int count = 0;     // Initialize hashmap.    HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();     // Insert array elements to hashmap    for (int i = 0; i < n; i++) {       if(mp.containsKey(arr[i])){        mp.put(arr[i], mp.get(arr[i])+1);      }else{        mp.put(arr[i], 1);      }    }     for (int i = 0; i < n; i++) {       int index = (int) (1.0 * k / arr[i]);       // If k is not power of two      if (index >= 0          && ((index - (int)(index)) == 0)          && mp.containsKey(k / arr[i])          && (index != arr[i])) {         count += mp.get(arr[i]) * mp.get(index);         // After counting erase the element        mp.remove(arr[i]);         mp.remove(index);      }       // If k is power of 2      if (index >= 0          && ((index - (int)(index)) == 0)          && mp.containsKey(k / arr[i])          && (index == arr[i])) {         // Pair count        count += (mp.get(arr[i])                  * (mp.get(arr[i]) - 1))          / 2;         // After counting erase the element;        mp.remove(arr[i]);      }    }     return count;  }   // Driver Code  public static void main(String[] args)  {     int arr[] = { 1, 2, 16, 4, 4, 4, 8 };    int N = arr.length;    int K = 16;    System.out.print(countPairsWithProductK(arr, N, K));   }} // This code is contributed by 29AjayKumar
# Python 3 program for the above approachfrom collections import defaultdict # Function to count# the total number of pairsdef countPairsWithProductK(arr, n, k):     count = 0     # Initialize hashmap.    mp = defaultdict(int)     # Insert array elements to hashmap    for i in range(n):         mp[arr[i]] += 1     for i in range(n):         index = 1.0 * k / arr[i]         # If k is not power of two        if (index >= 0            and ((index - (int)(index)) == 0)            and (k / arr[i]) in mp                and (index != arr[i])):             count += mp[arr[i]] * mp[index]             # After counting erase the element            del mp[arr[i]]             del mp[index]         # If k is power of 2        if (index >= 0            and ((index - (int)(index)) == 0)            and (k / arr[i]) in mp                and (index == arr[i])):             # Pair count            count += ((mp[arr[i]]                       * (mp[arr[i]] - 1)) / 2)             # After counting erase the element;            del mp[arr[i]]     return count # Driver Codeif __name__ == "__main__":     arr = [1, 2, 16, 4, 4, 4, 8]     N = len(arr)     K = 16     print(int(countPairsWithProductK(arr, N, K)))     # This code is contributed by ukasp.
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{   // Function to count  // the total number of pairs  static int countPairsWithProductK(    int []arr, int n, int k)   {     int count = 0;     // Initialize hashmap.    Dictionary<int,int> mp = new Dictionary<int,int>();     // Insert array elements to hashmap    for (int i = 0; i < n; i++) {       if(mp.ContainsKey(arr[i])){        mp[arr[i]] = mp[arr[i]]+1;      }else{        mp.Add(arr[i], 1);      }    }     for (int i = 0; i < n; i++) {       int index = (int) (1.0 * k / arr[i]);       // If k is not power of two      if (index >= 0          && ((index - (int)(index)) == 0)          && mp.ContainsKey(k / arr[i])          && (index != arr[i])) {         count += mp[arr[i]] * mp[index];         // After counting erase the element        mp.Remove(arr[i]);         mp.Remove(index);      }       // If k is power of 2      if (index >= 0          && ((index - (int)(index)) == 0)          && mp.ContainsKey(k / arr[i])          && (index == arr[i])) {         // Pair count        count += (mp[arr[i]]                  * (mp[arr[i]] - 1))          / 2;         // After counting erase the element;        mp.Remove(arr[i]);      }    }     return count;  }   // Driver Code  public static void Main(String[] args)  {     int []arr = { 1, 2, 16, 4, 4, 4, 8 };    int N = arr.Length;    int K = 16;    Console.Write(countPairsWithProductK(arr, N, K));   }} // This code is contributed by Rajput-Ji
<script>      // JavaScript code for the above approach      // Function to count      // the total number of pairs      function countPairsWithProductK(          arr, n, k) {           let count = 0;           // Initialize hashmap.          let mp = new Map();           // Insert array elements to hashmap          for (let i = 0; i < n; i++) {               if (mp.has(arr[i])) {                  mp.set(arr[i], mp.get(arr[i]) + 1);              }              else {                  mp.set(arr[i], 1);              }          }           for (let i = 0; i < n; i++) {               let index = 1.0 * k / arr[i];               // If k is not power of two              if (index >= 0                  && ((index - Math.floor(index)) == 0)                  && mp.has(k / arr[i])                  && (index != arr[i])) {                   count += mp.get(arr[i]) * mp.get(index);                   // After counting erase the element                  mp.delete(arr[i]);                   mp.delete(index);              }               // If k is power of 2              if (index >= 0                  && ((index - Math.floor(index)) == 0)                  && mp.has(k / arr[i])                  && (index == arr[i])) {                   // Pair count                  count += (mp.get(arr[i])                      * (mp.get(arr[i]) - 1))                      / 2;                   // After counting erase the element;                  mp.delete(arr[i]);              }          }           return count;      }       // Driver Code      let arr = [1, 2, 16, 4, 4, 4, 8];      let N = arr.length;      let K = 16;      document.write(countPairsWithProductK(arr, N, K));      // This code is contributed by Potta Lokesh  </script>
  
5
 
Time Complexity: O(N)Auxiliary Space: O(N)
 
lokeshpotta20
ukasp
29AjayKumar
Rajput-Ji
frequency-counting
Arrays
Combinatorial
Hash
Mathematical
Arrays
Hash
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Factorial of a large number