# Count of pairs in Array whose product is divisible by K

• Last Updated : 13 May, 2022

Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose product is divisible by K

Examples :

Input: A[] = [1, 2, 3, 4, 5], K = 2
Output: 7
Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are
(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).
Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.

Input: A[] = [1, 2, 3, 4], K = 5
Output: 0
Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5.

Naive approach: For finding the counts of all pairs we can  simply do a nested loop iteration and for each of element we can check all remaining elements whether their product is divisible by given key or not.

Time Complexity:  O(N2
Auxiliary Space: O(1)

Efficient approach: The problem can be solved efficiently using hashing based on the following observation:

• For checking the divisibility of product with K, better to deal with the GCD of number with K. This will remove all other factors from consideration. As, the number of divisors of K, would be very small when compared with the length of original array size.
• If GCD(a, K) * GCD(b, K) is divisible by key, then a * b should also be divisible by key.

Follow the steps mentioned below to solve the problem:

• Create a map which will store the GCD(A[i], K) as key and its occurrence as value.
• For each element of the array, check all elements of map, whether map’s element is divisible by X (X =  quotient when K is divide by GCD(A[i], K))
•  if yes add the occurrence of that element from map to answer.
• Also, keep incrementing the occurrence for each element’s GCD with key.
• Return the final count.

Below is the implementation of the above approach

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Program to count pairs whose product` `// is divisible by key` `long` `long` `countPairs(vector<``int``>& A, ``int` `                                         ``key)` `{` `    ``long` `long` `ans = 0;` `    ``unordered_map<``int``, ``int``> mp;`   `    ``for` `(``auto` `ele : A) {` `        ``// Calculate gcd of nums[i] and` `        ``// key` `        ``long` `long` `gcd = __gcd(key, ele);` `        ``long` `long` `x = key / gcd;`   `        ``// Iterate over all possible gcds` `        ``for` `(``auto` `it : mp)` `            ``if` `(it.first % x == 0)` `                ``// Add count to answer` `                ``ans += it.second;` `        ``// Add gcd to map` `        ``mp[gcd]++;` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``vector<``int``> A = { 1, 2, 3, 4, 5 };` `    ``int` `key = 2;`   `    ``cout << countPairs(A, key) << endl;` `    ``return` `0;` `}`

## Java

 `// JAVA program for the above approach` `import` `java.util.*;` `class` `GFG {`   `  ``public` `static` `int` `agcd(``int` `a, ``int` `b)` `  ``{` `    ``if` `(b == ``0``)` `      ``return` `a;` `    ``return` `agcd(b, a % b);` `  ``}`   `  ``// Program to count pairs whose product` `  ``// is divisible by key` `  ``public` `static` `long` `countPairs(``int``[] A, ``int` `key)` `  ``{` `    ``long` `ans = ``0``;` `    ``HashMap mp = ``new` `HashMap<>();`   `    ``for` `(``int` `i = ``0``; i < A.length; ++i) ` `    ``{`   `      ``// Calculate gcd of nums[i] and` `      ``// key` `      ``long` `gcd = agcd(key, A[i]);` `      ``long` `x = key / gcd;`   `      ``// Iterate over all possible gcds` `      ``for` `(Map.Entry it :` `           ``mp.entrySet())` `        ``if` `(it.getKey() % x == ``0``)` `          ``// Add count to answer` `          ``ans += it.getValue();` `      ``// Add gcd to map` `      ``if` `(mp.containsKey(gcd)) {` `        ``mp.put(gcd, mp.get(gcd) + ``1``);` `      ``}` `      ``else` `{` `        ``mp.put(gcd, ``1``);` `      ``}` `      ``// mp[gcd]++;` `    ``}`   `    ``return` `ans;` `  ``}`   `  ``// Driver code` `  ``public` `static` `void` `main(String[] args)` `  ``{` `    ``int` `A[] = ``new` `int``[] { ``1``, ``2``, ``3``, ``4``, ``5` `};` `    ``int` `key = ``2``;`   `    ``System.out.println(countPairs(A, key));` `  ``}` `}`   `// This code is contributed by Taranpreet`

## Python3

 `# Python3 Program to count pairs whose product` `# is divisible by key` `import` `math`   `def` `countPairs(A,key):` `    ``ans ``=` `0` `    ``mp ``=` `{}`   `    ``for` `ele ``in` `A:`   `        ``# Calculate gcd of nums[i] and` `        ``# key` `        ``gcd ``=` `math.gcd(ele, key)` `        ``x ``=` `key ``/``/` `gcd`   `        ``# Iterate over all possible gcds` `        ``for` `Key,value ``in` `mp.items():` `            ``if` `(Key ``%` `x ``=``=` `0``):` `                ``# Add count to answer` `                ``ans ``+``=` `value` `        ``# Add gcd to map` `        ``if``(gcd ``in` `mp):` `            ``mp[gcd] ``=` `mp[gcd] ``+` `1` `        ``else``:` `            ``mp[gcd] ``=` `1`   `    ``return` `ans`   `# Driver code`   `A ``=` `[ ``1``, ``2``, ``3``, ``4``, ``5` `]` `key ``=` `2`   `print``(countPairs(A, key))`   `# This code is contributed by shinjanpatra`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG {`   `  ``static` `int` `agcd(``int` `a, ``int` `b)` `  ``{` `    ``if` `(b == 0)` `      ``return` `a;` `    ``return` `agcd(b, a % b);` `  ``}`   `  ``// Program to count pairs whose product` `  ``// is divisible by key` `  ``static` `long` `countPairs(``int``[] A, ``int` `key)` `  ``{` `    ``long` `ans = 0;` `    ``Dictionary<``long``, ``int``> mp` `      ``= ``new` `Dictionary<``long``, ``int``>();`   `    ``for` `(``int` `i = 0; i < A.Length; ++i) {`   `      ``// Calculate gcd of nums[i] and` `      ``// key` `      ``long` `gcd = agcd(key, A[i]);` `      ``long` `x = key / gcd;`   `      ``// Iterate over all possible gcds` `      ``foreach``(KeyValuePair<``long``, ``int``> it ``in` `mp)` `      ``{`   `        ``if` `(it.Key % x == 0)` `          ``// Add count to answer` `          ``ans += it.Value;` `      ``}` `      ``// Add gcd to map` `      ``if` `(mp.ContainsKey(gcd)) {` `        ``mp[gcd] = mp[gcd] + 1;` `      ``}` `      ``else` `{` `        ``mp.Add(gcd, 1);` `      ``}` `      ``// mp[gcd]++;` `    ``}`   `    ``return` `ans;` `  ``}`   `  ``// Driver code` `  ``public` `static` `void` `Main()` `  ``{` `    ``int``[] A = { 1, 2, 3, 4, 5 };` `    ``int` `key = 2;`   `    ``Console.WriteLine(countPairs(A, key));` `  ``}` `}`   `// This code is contributed by Samim Hossain Mondal.`

## Javascript

 ``

Output

`7`

Time Complexity: O(N*K1/2)
Space Complexity: O(K1/2)

My Personal Notes arrow_drop_up
Recommended Articles
Page :