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):
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
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++
#include <bits/stdc++.h>
using namespace std;
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++)
countarr[vec[i]]++;
for ( int i = 1; i < 100001; i++) {
for ( int j = i; j < 100001; j = j + 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] % remaining_factor == 0)
j--;
ans += j;
}
ans /= 2;
return ans;
}
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5, 6 };
int k = 4;
cout << countPairs(vec, k) << endl;
}
|
Java
import java.util.*;
public class GFG {
static int [] countarr = new int [ 100001 ];
static int [] count_of_multiples = new int [ 100001 ];
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++)
countarr[vec[i]]++;
for ( int i = 1 ; i < 100001 ; i++) {
for ( int j = i; j < 100001 ; j = j + 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] % remaining_factor == 0 )
j--;
ans += j;
}
ans /= 2 ;
return ans;
}
public static void main(String args[])
{
int [] vec = { 1 , 2 , 3 , 4 , 5 , 6 };
int k = 4 ;
System.out.println(countPairs(vec, k));
}
}
|
Python3
import math
countarr = [ 0 ] * 100001
count_of_multiples = [ 0 ] * 100001
def countPairs(vec, k):
n = len (vec)
for i in range ( 0 , n):
countarr[vec[i]] + = 1
for i in range ( 1 , 100001 ):
j = i
while (j < 100001 ):
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] % remaining_factor = = 0 ):
j - = 1
ans + = j
ans / / = 2
return ans
vec = [ 1 , 2 , 3 , 4 , 5 , 6 ]
k = 4
print (countPairs(vec, k))
|
C#
using System;
class GFG {
static int [] countarr = new int [100001];
static int [] count_of_multiples = new int [100001];
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++)
countarr[vec[i]]++;
for ( int i = 1; i < 100001; i++) {
for ( int j = i; j < 100001; j = j + 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] % remaining_factor == 0)
j--;
ans += j;
}
ans /= 2;
return ans;
}
public static void Main()
{
int [] vec = { 1, 2, 3, 4, 5, 6 };
int k = 4;
Console.WriteLine(countPairs(vec, k));
}
}
|
Javascript
<script>
let countarr = new Array(100001).fill(0);
let count_of_multiples = new Array(100001).fill(0);
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++)
countarr[vec[i]]++;
for (let i = 1; i < 100001; i++) {
for (let j = i; j < 100001; j = j + 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] % remaining_factor == 0)
j--;
ans += j;
}
ans /= 2;
return ans;
}
let vec = [1, 2, 3, 4, 5, 6];
let k = 4;
document.write(countPairs(vec, k));
</script>
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...