Count divisible pairs in an array

27 Jun, 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++
Java
Python3
C#
PHP
Javascript
// 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 program to count// divisible pairs. class GFG {     // Function returns count// of divisible pairsstatic 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 Codepublic 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 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 codeif __name__=='__main__':    a = [1, 2, 3, 9]    n = len(a)    print(countDivisibles(a, n) ) # this code is contributed by# Smitha Dinesh Semwal   
// Java program to count// divisible pairs.using System; class GFG {     // Function returns count// of divisible pairsstatic 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 Codepublic 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 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));?>
<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>
4
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.
i) 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.
ii) For every element in the array denoted as arr[i], find all the factors of that element in O(sqrt(n)) time complexity.
iii) 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.
iv) Return the total count of such ordered pairs.
Below is the implementation of the above approach: 
C++
Java
// 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]==0int 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 codeint 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 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}
4
Time complexity: O(n3/2)
Auxiliary Space: O(n)
Smitha Dinesh Semwal
manishshaw1
_saurabh_jaiswal
pushpeshrajdx01
simmytarika5
codewithmini
divisibility
Mahindra Comviva
Arrays
Hash
Mahindra Comviva
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum