Count divisible pairs in an array
Last Updated :
18 Nov, 2022
Given an array, count pairs in the array such that one element of the pair divides the other.
Examples:
Input : arr[] = {1, 2, 3}
Output : 2
The two pairs are (1, 2) and (1, 3)
Input : arr[] = {2, 3, 5, 7}
Output: 0
Naive Approach: The brute force approach can be implemented by iterating through every element in the array and checking where we have pairs (i,j) such that arr[i]%arr[j]=0.
Below is the implementation of the above approach:
C++
// CPP program to count divisible pairs.
#include <bits/stdc++.h>
using namespace std;
int countDivisibles(int arr[], int n)
{
int res = 0;
// Iterate through all pairs
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++)
// Increment count if one divides
// other
if (arr[i] % arr[j] == 0 ||
arr[j] % arr[i] == 0)
res++;
return res;
}
int main()
{
int a[] = {1, 2, 3, 9};
int n = sizeof(a) / sizeof(a[0]);
cout << countDivisibles(a, n);
return 0;
}
Java
// Java program to count
// divisible pairs.
class GFG {
// Function returns count
// of divisible pairs
static int countDivisibles(int arr[],
int n)
{
int res = 0;
// Iterate through all pairs
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
// Increment count if
// one divides other
if (arr[i] % arr[j] == 0 ||
arr[j] % arr[i] == 0)
res++;
return res;
}
// Driver Code
public static void main(String[] args)
{
int a[] = new int[]{1, 2, 3, 9};
int n = a.length;
System.out.print(countDivisibles(a, n));
}
}
// This code is contributed by Smitha.
Python3
# Python3 program to count
# divisible pairs.
def countDivisibles(arr, n) :
res = 0
# Iterate through all pairs
for i in range(0, n) :
for j in range(i+1, n) :
# Increment count if one divides
# other
if (arr[i] % arr[j] == 0 or
arr[j] % arr[i] == 0) :
res+=1
return res
# Driver code
if __name__=='__main__':
a = [1, 2, 3, 9]
n = len(a)
print(countDivisibles(a, n) )
# this code is contributed by
# Smitha Dinesh Semwal
C#
// Java program to count
// divisible pairs.
using System;
class GFG {
// Function returns count
// of divisible pairs
static int countDivisibles(int []arr,
int n)
{
int res = 0;
// Iterate through all pairs
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
// Increment count if
// one divides other
if (arr[i] % arr[j] == 0 ||
arr[j] % arr[i] == 0)
res++;
return res;
}
// Driver Code
public static void Main(String[] args)
{
int[] a = new int[4] {1, 2, 3, 9};
int n = a.Length;
Console.Write(countDivisibles(a, n));
}
}
// This code is contributed by Smitha.
PHP
<?php
// PHP program to count divisible pairs.
function countDivisibles($arr, $n)
{
$res = 0;
// Iterate through all pairs
for ($i = 0; $i < $n; $i++)
for ($j = $i + 1; $j < $n; $j++)
// Increment count if one divides
// other
if ($arr[$i] % $arr[$j] == 0 ||
$arr[$j] % $arr[$i] == 0)
$res++;
return $res;
}
$a = array(1, 2, 3, 9);
$n = count($a);
echo (countDivisibles($a, $n));
?>
JavaScript
<script>
// JavaScript program to count divisible pairs.
function countDivisibles(arr, n) {
let res = 0;
// Iterate through all pairs
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
// Increment count if one divides
// other
if (arr[i] % arr[j] == 0 ||
arr[j] % arr[i] == 0)
res++;
return res;
}
let a = [1, 2, 3, 9];
let n = a.length;
document.write(countDivisibles(a, n));
</script>
Complexity Analysis:
- Time complexity: O(n2)
- Auxiliary Space: O(1)
Efficient Approach: This problem can be efficiently solved by counting the total factors of the element present in the array. As arr[i]%arr[j]==0 indicates that arr[j] is a divisor/factor of arr[i]. So for every element, we count the total number of its factors present in the array using an unordered map.
This approach can be implemented in the following steps.
- Store the frequency of all numbers present in the array. This can be stored in the unordered map so that we can access the frequency of any element in O(1) time complexity.
- For every element in the array denoted as arr[i], find all the factors of that element in O(sqrt(n)) time complexity.
- And for all factors count how many times that factor(let denote as f) occurred in the array as that many times arr[i]%f will be 0.
- Return the total count of such ordered pairs.
Below is the implementation of the above approach:
C++
// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the total
// count of pairs such that
// arr[i]%arr[j]==0
int total_count(int arr[], int n)
{
int count = 0;
// Storing the occurrence of
// every element in array in
// unordered_map
unordered_map<int, int> freq;
for(int i=0;i<n;i++)
{
freq[arr[i]]++;
}
// Iterating through every element
// and finding all the divisors of
// that element and then checking
// how many of them are present
// in array arr[]
for(int i=0;i<n;i++)
{
for (int j=1;j<=sqrt(arr[i]);j++)
{
if(arr[i]%j==0)
{
if(arr[i]==j*j)
{ // If divisors are equal,
// then take only one as
// it will be perfect square
// root of arr[i]
count+=freq[j];
}
else
{
// Else take both j and arr[i]/j
// as both will be divisors
count+=freq[j]+ freq[arr[i]/j];
}
}
}
// As all the elements is divisible
// by itself and is counted in freq[]
// so reducing its count
count=count-1;
}
// Returning final count
return count;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 9 };
int N = sizeof(arr) / sizeof(arr[0]);
cout<<total_count(arr,N);
return 0;
}
// This code is contributed by Pushpesh Raj
Java
// Java program to count
// divisible pairs.
import java.util.*;
public class GFG {
// Function to return the total
// count of pairs such that
// arr[i]%arr[j]==0
public static int total_count(int[] arr, int n)
{
int count = 0;
// Storing the occurrence of
// every element in array in
// unordered_map
HashMap<Integer, Integer> freq
= new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
if (!freq.containsKey(arr[i])) {
freq.put(arr[i], 1);
}
else {
freq.put(arr[i], freq.get(arr[i]) + 1);
}
}
// Iterating through every element
// and finding all the divisors of
// that element and then checking
// how many of them are present
// in array arr[]
for (int i = 0; i < n; i++) {
for (int j = 1; j <= Math.sqrt(arr[i]); j++) {
if (arr[i] % j == 0) {
if (arr[i] == j * j) { // If divisors
// are equal,
// then take only one as
// it will be perfect square
// root of arr[i]
count += freq.get(j);
}
else {
// Else take both j and arr[i]/j
// as both will be divisors
count += freq.get(j)
+ freq.get(arr[i] / j);
}
}
}
// As all the elements is divisible
// by itself and is counted in freq[]
// so reducing its count
count = count - 1;
}
// Returning final count
return count;
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 9 };
int N = arr.length;
System.out.print(total_count(arr, N));
}
// This code is contributed by Aarti_Rathi
}
Python3
# Python program to count divisible pairs.
import math
# Function to return the total count of pairs such
# that arr[i]%arr[j]==0
def total_count(arr, N):
count = 0
# Storing the occurrence of every element in array
# in dictionary
freq = {}
for i in range(0, N):
if arr[i] not in freq:
freq[arr[i]] = 1
else:
freq[arr[i]] += 1
# Iterating through every element and finding all the
# divisors of that element and then checking how many
# of them are present in array arr[]
for i in range(0, N):
for j in range(1, int(math.sqrt(arr[i]))+1):
if arr[i] % j == 0:
if arr[i] == j*j:
# If divisors are equal, then take only
# one as it will be perfect square root
# of arr[i]
count += freq[j]
else:
# Else take both j and arr[i]/j as both
# will be divisors
count += freq[j]+freq[arr[i]/j]
# As all the elements is divisible by itself and
# is counted in freq[] so reducing its count
count = count-1
# returning final count
return count
arr = [1, 2, 3, 9]
N = len(arr)
print(total_count(arr, N))
# This code is contributed by lokesh (lokeshmvs21).
C#
// C# program to count
// divisible pairs.
using System;
using System.Collections.Generic;
public class GFG {
// Function to return the total
// count of pairs such that
// arr[i]%arr[j]==0
public static int total_count(int[] arr, int n)
{
int count = 0;
// Storing the occurrence of
// every element in array in
// unordered_map
Dictionary<int, int> freq
= new Dictionary<int, int>();
for (int i = 0; i < n; i++) {
if (!freq.ContainsKey(arr[i])) {
freq[arr[i]] = 1;
}
else {
freq[arr[i]] += 1;
}
}
// Iterating through every element
// and finding all the divisors of
// that element and then checking
// how many of them are present
// in array arr[]
for (int i = 0; i < n; i++) {
for (int j = 1; j <= Math.Sqrt(arr[i]); j++) {
if (arr[i] % j == 0) {
if (arr[i] == j * j) { // If divisors
// are equal,
// then take only one as
// it will be perfect square
// root of arr[i]
count += freq[j];
}
else {
// Else take both j and arr[i]/j
// as both will be divisors
count += freq[j] + freq[arr[i] / j];
}
}
}
// As all the elements is divisible
// by itself and is counted in freq[]
// so reducing its count
count = count - 1;
}
// Returning final count
return count;
}
// Driver code
public static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 9 };
int N = arr.Length;
Console.Write(total_count(arr, N));
}
}
// This code is contributed by phasing17
JavaScript
// Javascript program to count
// divisible pairs.
function total_count(arr,n)
{
let count = 0;
// Storing the occurrence of
// every element in array in
// unordered_map
let freq = new Map();
for (let i = 0; i < n; i++) {
if (!freq.has(arr[i])) {
freq.set(arr[i], 1);
}
else {
freq.set(arr[i], freq.get(arr[i]) + 1);
}
}
// Iterating through every element
// and finding all the divisors of
// that element and then checking
// how many of them are present
// in array arr[]
for (let i = 0; i < n; i++) {
for (let j = 1; j <= Math.sqrt(arr[i]); j++) {
if (arr[i] % j == 0) {
if (arr[i] == j * j) { // If divisors
// are equal,
// then take only one as
// it will be perfect square
// root of arr[i]
count += freq.get(j);
}
else {
// Else take both j and arr[i]/j
// as both will be divisors
count += freq.get(j) + freq.get(arr[i] / j);
}
}
}
// As all the elements is divisible
// by itself and is counted in freq[]
// so reducing its count
count = count - 1;
}
// Returning final count
return count;
}
let arr = [ 1, 2, 3, 9 ];
let N = arr.length;
console.log(total_count(arr, N));
// This code is contributed by aadityaburujwale.
Complexity Analysis:
- Time complexity: O(n3/2)
- Auxiliary Space: O(n)
Similar Reads
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
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 product is divisible by K 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 = 4Output: 6Explanation: The pairs of indices (0, 3), (1, 3), (2, 3), (3, 4), (3, 5) and (1, 5) satisfy the condition as their pro
11 min read
Count number of pairs not divisible by any element in the array Given an array arr[] of size N, the task is to count the number of pairs of integers (i, j) for which there does not exist an integer k such that arr[i] is divisible by arr[k] and arr[j] is divisible by arr[k], such that k can be any index between [0, N - 1]. Examples: Input: N = 4, arr[] = {2, 4, 5
5 min read
Check If Array Pair Sums Divisible by k Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k.Examples: Input: arr[] = [9, 7, 5, 3], k = 6 Output: True We can divide the array into (9, 3) and (7, 5). Sum of both of these
15 min read