Open In App

Count divisible pairs in an array

Last Updated : 18 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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>


Output

4

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.

  1. 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.
  2. For every element in the array denoted as arr[i], find all the factors of that element in O(sqrt(n)) time complexity.
  3. 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.
  4. 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.


Output

4

Complexity Analysis:

  • Time complexity: O(n3/2)
  • Auxiliary Space: O(n)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads