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 = 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.
Algorithm:
- Initialize a counter variable count to 0.
- Loop i from 0 to N-1
- Loop j from i+1 to N-1
i. If A[i]*A[j] is divisible by K, then increment count by 1.
- Return count as the final result.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countPairs( int arr[], int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if ((arr[i] * arr[j]) % k == 0) {
count++;
}
}
}
return count;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 2;
int count = countPairs(arr, n, k);
cout << count << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
static int countPairs( int [] arr, int n, int k) {
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if ((arr[i] * arr[j]) % k == 0 ) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 3 , 4 , 5 };
int n = arr.length;
int k = 2 ;
int count = countPairs(arr, n, k);
System.out.println(count);
}
}
|
Python3
def countPairs(arr, k):
count = 0
for i in range ( len (arr)):
for j in range (i + 1 , len (arr)):
if (arr[i] * arr[j]) % k = = 0 :
count + = 1
return count
arr = [ 1 , 2 , 3 , 4 , 5 ]
k = 2
count = countPairs(arr, k)
print (count)
|
C#
using System;
class Program
{
static int CountPairs( int [] arr, int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
if ((arr[i] * arr[j]) % k == 0)
{
count++;
}
}
}
return count;
}
static void Main()
{
int [] arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
int k = 2;
int count = CountPairs(arr, n, k);
Console.WriteLine(count);
}
}
|
Javascript
function countPairs(arr, k) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if ((arr[i] * arr[j]) % k === 0) {
count++;
}
}
}
return count;
}
let arr = [1, 2, 3, 4, 5];
let k = 2;
let count = countPairs(arr, k);
console.log(count);
|
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++
#include <bits/stdc++.h>
using namespace std;
long long countPairs(vector< int >& A, int
key)
{
long long ans = 0;
unordered_map< int , int > mp;
for ( auto ele : A) {
long long gcd = __gcd(key, ele);
long long x = key / gcd;
for ( auto it : mp)
if (it.first % x == 0)
ans += it.second;
mp[gcd]++;
}
return ans;
}
int main()
{
vector< int > A = { 1, 2, 3, 4, 5 };
int key = 2;
cout << countPairs(A, key) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int agcd( int a, int b)
{
if (b == 0 )
return a;
return agcd(b, a % b);
}
public static long countPairs( int [] A, int key)
{
long ans = 0 ;
HashMap<Long, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < A.length; ++i)
{
long gcd = agcd(key, A[i]);
long x = key / gcd;
for (Map.Entry<Long, Integer> it :
mp.entrySet())
if (it.getKey() % x == 0 )
ans += it.getValue();
if (mp.containsKey(gcd)) {
mp.put(gcd, mp.get(gcd) + 1 );
}
else {
mp.put(gcd, 1 );
}
}
return ans;
}
public static void main(String[] args)
{
int A[] = new int [] { 1 , 2 , 3 , 4 , 5 };
int key = 2 ;
System.out.println(countPairs(A, key));
}
}
|
Python3
import math
def countPairs(A,key):
ans = 0
mp = {}
for ele in A:
gcd = math.gcd(ele, key)
x = key / / gcd
for Key,value in mp.items():
if (Key % x = = 0 ):
ans + = value
if (gcd in mp):
mp[gcd] = mp[gcd] + 1
else :
mp[gcd] = 1
return ans
A = [ 1 , 2 , 3 , 4 , 5 ]
key = 2
print (countPairs(A, key))
|
C#
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);
}
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) {
long gcd = agcd(key, A[i]);
long x = key / gcd;
foreach (KeyValuePair< long , int > it in mp)
{
if (it.Key % x == 0)
ans += it.Value;
}
if (mp.ContainsKey(gcd)) {
mp[gcd] = mp[gcd] + 1;
}
else {
mp.Add(gcd, 1);
}
}
return ans;
}
public static void Main()
{
int [] A = { 1, 2, 3, 4, 5 };
int key = 2;
Console.WriteLine(countPairs(A, key));
}
}
|
Javascript
<script>
function _gcd(x,y){
if (!y) return x;
return _gcd(y,x%y);
}
function countPairs(A,key){
let ans = 0
let mp = new Map()
for (let ele of A){
let gcd = _gcd(ele,key)
let x = Math.floor(key / gcd)
for (let [Key,value] of mp){
if (Key % x == 0)
ans += value
}
if (mp.has(gcd))
mp.set(gcd,mp.get(gcd)+1)
else
mp.set(gcd,1)
}
return ans
}
let A = [ 1, 2, 3, 4, 5 ]
let key = 2
document.write(countPairs(A, key))
</script>
|
Time Complexity: O(N*K1/2)
Space Complexity: O(K1/2)
Last Updated :
26 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...