Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count pairs made up of an element divisible by the other from an array consisting of powers of 2

  • Last Updated : 18 Jan, 2022

Given an array arr[] consisting of N powers of 2, the task is to count the number of pairs (arr[i], arr[j]) such that i < j and arr[j] is divisible by arr[i].

Examples:

Input: arr[] = {4, 16, 8, 64}
Output: 5
Explanation:
The pairs satisfying the given condition are {4, 16}, {4, 8}, {4, 64}, {16, 64}, {8, 64}.

Input: arr[] = {2, 4, 8, 16}
Output: 6
Explanation:
The pairs satisfying the given condition are {2, 4}, {2, 8}, {2, 16}, {4, 8}, {4, 16}, {8, 16}.

Naive Approach: The simplest approach is to generate all pairs of the given array arr[] and for each pair, check if arr[j] % arr[i] is 0 or not. If found to be true, increment count by 1. Finally, print the value of count after checking for all pairs. 
Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is based on the observation that any power of 2 has only one set bit in its binary representation. For any such element arr[j], all the powers of 2 which have their set bits at a position less than or equal to the position of a set bit of arr[j], will satisfy the given condition. Follow the steps below to solve the problem:

  • Initialize an auxiliary array setBits of size equal to 31, and initialize count as 0 to store the number of required pairs.
  • Traverse the array arr[] using the variable i and perform the following operations:
  • After completing the above steps, print the value of count as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of
// pairs as per the given conditions
void numberOfPairs(int arr[], int N)
{
    // Initialize array set_bits as 0
    int set_bits[31] = { 0 };
 
    // Store the total number of
    // required pairs
    int count = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Store arr[i] in x
        int x = arr[i];
 
        // Store the position of the
        // leftmost set bit in arr[i]
        int bitpos = -1;
 
        while (x > 0) {
 
            // Increase bit position
            bitpos++;
 
            // Divide by 2 to shift bits
            // in right at each step
            x /= 2;
        }
 
        // Count of pairs for index i
        // till its set bit position
        for (int j = 0;
             j <= bitpos; j++) {
            count += set_bits[j];
        }
 
        // Increasing count of set bit
        // position of current element
        set_bits[bitpos]++;
    }
 
    // Print the answer
    cout << count;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 16, 8, 64 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    numberOfPairs(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to count the number of
// pairs as per the given conditions
static void numberOfPairs(int arr[], int N)
{
   
    // Initialize array set_bits as 0
    int []set_bits = new int[31];
    Arrays.fill(set_bits, 0);
 
    // Store the total number of
    // required pairs
    int count = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
    {
 
        // Store arr[i] in x
        int x = arr[i];
 
        // Store the position of the
        // leftmost set bit in arr[i]
        int bitpos = -1;
        while (x > 0)
        {
 
            // Increase bit position
            bitpos++;
 
            // Divide by 2 to shift bits
            // in right at each step
            x /= 2;
        }
 
        // Count of pairs for index i
        // till its set bit position
        for (int j = 0;
             j <= bitpos; j++)
        {
            count += set_bits[j];
        }
 
        // Increasing count of set bit
        // position of current element
        set_bits[bitpos]++;
    }
 
    // Print the answer
    System.out.println(count);
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 4, 16, 8, 64 };
    int N = arr.length;
 
    // Function Call
    numberOfPairs(arr, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR.

Python3




# Python3 program for the above approach
 
# Function to count the number of
# pairs as per the given conditions
def numberOfPairs(arr, N):
   
    # Initialize array set_bits as 0
    set_bits = [0]*31
 
    # Store the total number of
    # required pairs
    count = 0
 
    # Traverse the array arr[]
    for i in range(N):
 
        # Store arr[i] in x
        x = arr[i]
 
        # Store the position of the
        # leftmost set bit in arr[i]
        bitpos = -1
 
        while (x > 0):
 
            # Increase bit position
            bitpos += 1
 
            # Divide by 2 to shift bits
            # in right at each step
            x //= 2
 
        # Count of pairs for index i
        # till its set bit position
        for j in range(bitpos + 1):
            count += set_bits[j]
 
        # Increasing count of set bit
        # position of current element
        set_bits[bitpos] += 1
 
    # Prthe answer
    print (count)
 
# Driver Code
if __name__ == '__main__':
    arr = [4, 16, 8, 64]
    N = len(arr)
 
    # Function Call
    numberOfPairs(arr, N)
 
    # This code is contributed by mohit kumar 29.

C#




// C# program for the above approach
using System;
class GFG
{
 
// Function to count the number of
// pairs as per the given conditions
static void numberOfPairs(int[] arr, int N)
{
   
    // Initialize array set_bits as 0
    int []set_bits = new int[31];
    for (int i = 0; i < N; i++)
    {
        set_bits[i] = 0;
    }
 
    // Store the total number of
    // required pairs
    int count = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
    {
 
        // Store arr[i] in x
        int x = arr[i];
 
        // Store the position of the
        // leftmost set bit in arr[i]
        int bitpos = -1;
        while (x > 0)
        {
 
            // Increase bit position
            bitpos++;
 
            // Divide by 2 to shift bits
            // in right at each step
            x /= 2;
        }
 
        // Count of pairs for index i
        // till its set bit position
        for (int j = 0;
             j <= bitpos; j++)
        {
            count += set_bits[j];
        }
 
        // Increasing count of set bit
        // position of current element
        set_bits[bitpos]++;
    }
 
    // Print the answer
    Console.Write(count);
}
 
// Driver Code
static public void Main()
{
    int[] arr = { 4, 16, 8, 64 };
    int N = arr.Length;
 
    // Function Call
    numberOfPairs(arr, N);
}
}
 
// This code is contributed by splevel62.

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to count the number of
// pairs as per the given conditions
function numberOfPairs(arr, N)
{
    
    // Initialize array set_bits as 0
    let set_bits = [];
    for (let i = 0; i < 31; i++)
    {
        set_bits[i] = 0;
    }
  
    // Store the total number of
    // required pairs
    let count = 0;
  
    // Traverse the array arr[]
    for (let i = 0; i < N; i++)
    {
  
        // Store arr[i] in x
        let x = arr[i];
  
        // Store the position of the
        // leftmost set bit in arr[i]
        let bitpos = -1;
        while (x > 0)
        {
  
            // Increase bit position
            bitpos++;
  
            // Divide by 2 to shift bits
            // in right at each step
            x = Math.floor( x / 2 );
        }
  
        // Count of pairs for index i
        // till its set bit position
        for (let j = 0;
             j <= bitpos; j++)
        {
            count += set_bits[j];
        }
  
        // Increasing count of set bit
        // position of current element
        set_bits[bitpos]++;
    }
  
    // Print the answer
    document.write(count);
}
 
// Driver Code
 
      let arr = [ 4, 16, 8, 64 ];
    let N = arr.length;
  
    // Function Call
    numberOfPairs(arr, N);
  
</script>
Output: 
5

 

Time Complexity: O(N*log M), where M is the largest element in the array.
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!