Count pairs in Array whose product is divisible by K
Last Updated : 11 Oct, 2023
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.
Brute Force Approach:
- Define a function 'countPairsDivisibleByK' that takes vector 'vec' and integer 'K' as input and returns an integer as output.
- Initialize an integer 'count' to 0 and calculate the size of the vector 'vec' and store it in 'n'.
- Loop through each pair of indices in 'vec' using nested loops with indices 'i' and 'j', where 'i' ranges from 0 to n-2 and 'j' ranges from i+1 to n-1.
- Check if the product of 'vec[i]' and 'vec[j]' is divisible by 'K', and if so, increment 'count'.
- Return the final value of 'count'.
Below is the implementation of the above approach:
C++ #include <iostream> #include <vector> using namespace std; int countPairsDivisibleByK(vector<int>& vec, int K) { int count = 0; int n = vec.size(); for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if((vec[i] * vec[j]) % K == 0) { count++; } } } return count; } int main() { vector<int> vec1 = {1, 2, 3, 4, 5, 6}; int K = 4; cout << countPairsDivisibleByK(vec1, K) << endl; return 0; }
Java import java.util.*; public class Main { public static void main(String[] args) { List<Integer> vec1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6)); int K = 4; System.out.println(countPairsDivisibleByK(vec1, K)); } public static int countPairsDivisibleByK(List<Integer> vec, int K) { int count = 0; int n = vec.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((vec.get(i) * vec.get(j)) % K == 0) { count++; } } } return count; } }
Python3 def countPairsDivisibleByK(vec, K): # Function to count the number of pairs in the list # whose product is divisible by K count = 0 n = len(vec) for i in range(n): for j in range(i + 1, n): if (vec[i] * vec[j]) % K == 0: count += 1 return count # Driver code def main(): vec1 = [1, 2, 3, 4, 5, 6] K = 4 print(countPairsDivisibleByK(vec1, K)) if __name__ == "__main__": main()
C# using System; using System.Collections.Generic; class Program { static int CountPairsDivisibleByK(List<int> list, int K) { int count = 0; int n = list.Count; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((list[i] * list[j]) % K == 0) { count++; } } } return count; } static void Main() { List<int> list1 = new List<int> { 1, 2, 3, 4, 5, 6 }; int K = 4; Console.WriteLine(CountPairsDivisibleByK(list1, K)); } }
JavaScript function countPairsDivisibleByK(arr, K) { let count = 0; const n = arr.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { if ((arr[i] * arr[j]) % K === 0) { count++; } } } return count; } function main() { const arr1 = [1, 2, 3, 4, 5, 6]; const K = 4; console.log(countPairsDivisibleByK(arr1, K)); } main();
Time Complexity: O(n^2), where n is the size of the input array.
Auxiliary Space: O(1), as we are not using any extra space.
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>
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Similar Reads
Count of pairs in Array whose product is divisible by K
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 = 2Output: 7Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are(0, 1), (0, 3), (1, 2)
9 min read
Count pairs in array whose sum is divisible by K
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K. Note: This question is a generalized version of this Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 Explanation : There are five pairs possible whose sum
10 min read
Count pairs in array whose sum is divisible by 4
Given a array if 'n' positive integers. Count number of pairs of integers in the array that have the sum divisible by 4. Examples : Input: {2, 2, 1, 7, 5}Output: 3Explanation:Only three pairs are possible whose sumis divisible by '4' i.e., (2, 2), (1, 7) and (7, 5)Input: {2, 2, 3, 5, 6}Output: 4Reco
10 min read
Count sub-arrays whose product is divisible by k
Given an integer K and an array arr[], the task is to count all the sub-arrays whose product is divisible by K.Examples: Input: arr[] = {6, 2, 8}, K = 4 Output: 4 Required sub-arrays are {6, 2}, {6, 2, 8}, {2, 8}and {8}.Input: arr[] = {9, 1, 14}, K = 6 Output: 1 Naive approach: Run nested loops and
15+ min read
Count pairs whose products exist in array
Given an array, count those pair whose product value is present in array. Examples: Input : arr[] = {6, 2, 4, 12, 5, 3}Output : 3 All pairs whose product exist in array (6 , 2) (2, 3) (4, 3) Input : arr[] = {3, 5, 2, 4, 15, 8}Output : 2 A Simple solution is to generate all pairs of given array and c
15+ min read
Count pairs in an array whose absolute difference is divisible by K
Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The p
14 min read
Count subsets having product divisible by K
Given an array arr[] of size N and an integer K, the task is to count the number of subsets from the given array with the product of elements divisible by K Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 60Output: 4Explanation: Subsets whose product of elements is divisible by K(= 60) are { {1, 2, 3,
9 min read
Count number of pairs in array having sum divisible by K | SET 2
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K.Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 There are five pairs possible whose sum Is divisible by '4' i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3)I
6 min read
Count pairs in an array whose absolute difference is divisible by K | Using Map
Given an array, arr[] of N elements and an integer K, the task is to find the number of pairs (i, j) such that the absolute value of (arr[i] - arr[j]) is a multiple of K. Examples: Input: N = 4, K = 2, arr[] = {1, 2, 3, 4}Output: 2Explanation: Total 2 pairs exists in the array with absolute differen
7 min read
Count pairs in a sorted array whose product is less than k
Given a sorted integer array and number k, the task is to count pairs in an array whose product is less than x. Examples: Input: A = {2, 3, 5, 6}, k = 16 Output: 4 Pairs having product less than 16: (2, 3), (2, 5), (2, 6), (3, 5) Input: A = {2, 3, 4, 6, 9}, k = 20 Output: 6 Pairs having product less
12 min read