Skip to content
Related Articles

Related Articles

Count pairs in Array whose product is divisible by K

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 24 Mar, 2022
View Discussion
Improve Article
Save Article

Given a array vec and an integer K, count the number of pairs (i, j) such that vec[i]*vec[j] is divisible by K where i<j.

Examples:

Input: vec = {1, 2, 3, 4, 5, 6}, K = 4
Output: 6
Explanation: The pairs of indices (0, 3), (1, 3), (2, 3), (3, 4), (3, 5) and (1, 5) satisfy the condition as their products respectively are 4, 8, 12, 20, 24, 12 
which are divisible by k=4.
Since there are 6 pairs the count will be 6.

Input: vec = {1, 2, 3, 4}, K = 2
Output: 5
Explanation: The pairs of indices (0, 1), (1, 2), (1, 3), (0, 3), (2, 3) satisfy the condition as their products respectively are 2, 6, 8, 4, 12 which are divisible by k=2.
Since there are 5 pairs the count will be 5.

 

Naive Approach: The most simple approach to solve this problem is to find all pairs, and for each pair, check if their product is divisible by K.

Time Complexity: O(N^2)
Auxiliary space: O(1)

Efficient Approach: The above problem can be solved efficiently with the help of GCD.

We know that product of A and B is divisible by a number B if GCD(A, B) = B.

Similarly (vec[i] * vec[j]) will be divisible by K if their GCD is K. 

Follow the below steps to solve the problem: 

  • Create a countarr of size 10^5 + 1 to precalculate the count of how many numbers are divisible by a number num(say) (for all num 1 to 10^5).
  • Then we just need to loop for each element or vector and finding out the remaining number( remaining_factor) needed to be multiplied to it so as to make the GCD equals to k.
  • Then for this number the count of pairs will be as much as the multiple of remaining_factor present in array (ignoring the number itself).
  • Thus adding count of pairs for each i in vec we will get our answer, we will  divide the final answer by 2 as we have counted each pair twice for any pair (i, j) and remove the duplicates.

Below is the implementation of the above approach:

C++




// C++ program for Count number of pairs
// in a vector such that
// product is divisible by K
 
#include <bits/stdc++.h>
using namespace std;
 
// Precalculate count array to see numbers
// that are divisible by a number num (say)
// for all num 1 to 10^5
int countarr[100001];
int count_of_multiples[100001];
 
long long countPairs(vector<int>& vec, int k)
{
    int n = vec.size();
    for (int i = 0; i < n; i++)
 
        // counting frequency of  each
        // element in vector
        countarr[vec[i]]++;
 
    for (int i = 1; i < 100001; i++) {
        for (int j = i; j < 100001; j = j + i)
 
            // counting total elements present in
            // array which are multiple of i
            count_of_multiples[i] += countarr[j];
    }
 
    long long ans = 0;
    for (int i = 0; i < n; i++) {
        long long factor = __gcd(k, vec[i]);
        long long remaining_factor = (k / factor);
        long long j = count_of_multiples[remaining_factor];
 
        // if vec[i] itself is multiple of
        // remaining factor then we to ignore
        // it as  i!=j
        if (vec[i] % remaining_factor == 0)
            j--;
        ans += j;
    }
 
    // as we have counted any distinct pair
    // (i, j) two times, we need to take them
    // only once
    ans /= 2;
 
    return ans;
}
 
// Driver code
int main()
{
    vector<int> vec = { 1, 2, 3, 4, 5, 6 };
    int k = 4;
    cout << countPairs(vec, k) << endl;
}


Java




// Java program for Count number of pairs
// in a vector such that
// product is divisible by K
import java.util.*;
public class GFG {
 
  // Precalculate count array to see numbers
  // that are divisible by a number num (say)
  // for all num 1 to 10^5
  static int[] countarr = new int[100001];
  static int[] count_of_multiples = new int[100001];
 
  // Recursive function to return
  // gcd of a and b
  static int gcd(int a, int b)
  {
    if (b == 0)
      return a;
    return gcd(b, a % b);
  }
 
  static long countPairs(int[] vec, int k)
  {
    int n = vec.length;
    for (int i = 0; i < n; i++)
 
      // counting frequency of  each
      // element in vector
      countarr[vec[i]]++;
 
    for (int i = 1; i < 100001; i++) {
      for (int j = i; j < 100001; j = j + i)
 
        // counting total elements present in
        // array which are multiple of i
        count_of_multiples[i] += countarr[j];
    }
 
    long ans = 0;
    for (int i = 0; i < n; i++) {
      long factor = gcd(k, vec[i]);
      long remaining_factor = (k / factor);
      long j = count_of_multiples[(int)remaining_factor];
 
      // if vec[i] itself is multiple of
      // remaining factor then we to ignore
      // it as  i!=j
      if (vec[i] % remaining_factor == 0)
        j--;
      ans += j;
    }
 
    // as we have counted any distinct pair
    // (i, j) two times, we need to take them
    // only once
    ans /= 2;
 
    return ans;
  }
 
  // Driver code
  public static void main(String args[])
  {
    int[] vec = { 1, 2, 3, 4, 5, 6 };
    int k = 4;
    System.out.println(countPairs(vec, k));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3




# Python program for Count number of pairs
# in a vector such that
# product is divisible by K
import math
 
# Precalculate count array to see numbers
# that are divisible by a number num (say)
# for all num 1 to 10^5
countarr = [0] * 100001
count_of_multiples = [0] * 100001
 
def countPairs(vec, k):
 
    n = len(vec)
    for i in range(0, n):
 
        # counting frequency of  each
        # element in vector
        countarr[vec[i]] += 1
 
    for i in range(1, 100001):
        j = i
        while(j < 100001):
 
            # counting total elements present in
            # array which are multiple of i
            count_of_multiples[i] += countarr[j]
            j += i
 
    ans = 0
    for i in range(0, n):
        factor = math.gcd(k, vec[i])
        remaining_factor = (k // factor)
        j = count_of_multiples[remaining_factor]
 
        # if vec[i] itself is multiple of
        # remaining factor then we to ignore
        # it as  i!=j
        if (vec[i] % remaining_factor == 0):
            j -= 1
        ans += j
 
    # as we have counted any distinct pair
    # (i, j) two times, we need to take them
    # only once
    ans //= 2
    return ans
 
# Driver code
vec = [1, 2, 3, 4, 5, 6]
k = 4
print(countPairs(vec, k))
 
# This code is contributed by Samim Hossain Mondal.


C#




// C# program for Count number of pairs
// in a vector such that
// product is divisible by K
 
using System;
class GFG {
 
  // Precalculate count array to see numbers
  // that are divisible by a number num (say)
  // for all num 1 to 10^5
  static int[] countarr = new int[100001];
  static int[] count_of_multiples = new int[100001];
 
  // Recursive function to return
  // gcd of a and b
  static int gcd(int a, int b)
  {
    if (b == 0)
      return a;
    return gcd(b, a % b);
  }
 
  static long countPairs(int[] vec, int k)
  {
    int n = vec.Length;
    for (int i = 0; i < n; i++)
 
      // counting frequency of  each
      // element in vector
      countarr[vec[i]]++;
 
    for (int i = 1; i < 100001; i++) {
      for (int j = i; j < 100001; j = j + i)
 
        // counting total elements present in
        // array which are multiple of i
        count_of_multiples[i] += countarr[j];
    }
 
    long ans = 0;
    for (int i = 0; i < n; i++) {
      long factor = gcd(k, vec[i]);
      long remaining_factor = (k / factor);
      long j = count_of_multiples[remaining_factor];
 
      // if vec[i] itself is multiple of
      // remaining factor then we to ignore
      // it as  i!=j
      if (vec[i] % remaining_factor == 0)
        j--;
      ans += j;
    }
 
    // as we have counted any distinct pair
    // (i, j) two times, we need to take them
    // only once
    ans /= 2;
 
    return ans;
  }
 
  // Driver code
  public static void Main()
  {
    int[] vec = { 1, 2, 3, 4, 5, 6 };
    int k = 4;
    Console.WriteLine(countPairs(vec, k));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
    // JavaScript program for Count number of pairs
    // in a vector such that
    // product is divisible by K
 
    // Precalculate count array to see numbers
    // that are divisible by a number num (say)
    // for all num 1 to 10^5
    let countarr = new Array(100001).fill(0);
    let count_of_multiples = new Array(100001).fill(0);
 
    // Function for __gcd
    const __gcd = (a, b) => {
        if (a % b == 0) return b;
 
        return __gcd(b, a % b);
    }
 
    const countPairs = (vec, k) => {
        let n = vec.length;
        for (let i = 0; i < n; i++)
 
            // counting frequency of each
            // element in vector
            countarr[vec[i]]++;
 
        for (let i = 1; i < 100001; i++) {
            for (let j = i; j < 100001; j = j + i)
 
                // counting total elements present in
                // array which are multiple of i
                count_of_multiples[i] += countarr[j];
        }
 
        let ans = 0;
        for (let i = 0; i < n; i++) {
            let factor = __gcd(k, vec[i]);
            let remaining_factor = (k / factor);
            let j = count_of_multiples[remaining_factor];
 
            // if vec[i] itself is multiple of
            // remaining factor then we to ignore
            // it as i!=j
            if (vec[i] % remaining_factor == 0)
                j--;
            ans += j;
        }
 
        // as we have counted any distinct pair
        // (i, j) two times, we need to take them
        // only once
        ans /= 2;
        return ans;
    }
 
    // Driver code
    let vec = [1, 2, 3, 4, 5, 6];
    let k = 4;
    document.write(countPairs(vec, k));
 
// This code is contributed by rakeshsahni
 
</script>


 
 

Output: 

6

 

 

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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!