Number of pairs whose product is a power of 2
Given an array arr[] consisting of N integers, the task is to count the total number of pairs of array elements from the given array such that arr[i] * arr[j] is the power of 2.
Examples:
Input: arr[] = {2, 4, 7, 2}
Output: 3
Explanation:
arr[0] * arr[1] = 8
arr[0] * arr[3] = 4
arr[1] * arr[3] = 8
Input: arr[] = {8, 1, 12, 4, 2}
Output: 6
Approach: The idea is based upon the fact that a number is a power of 2 if it contains only 2 as its prime factor. Therefore, all its divisors are also a power of 2. Follow the steps below to solve the problem:
- Traverse the given array.
- For every array element, check if it is a power of 2 or not. Increase the count of such elements
- Finally, print (count * (count – 1)) / 2 as the required count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countPairs( int arr[], int N)
{
int countPowerof2 = 0;
for ( int i = 0; i < N; i++) {
if (__builtin_popcount(arr[i]) == 1)
countPowerof2++;
}
int desiredPairs
= (countPowerof2
* (countPowerof2 - 1))
/ 2;
cout << desiredPairs << ' ' ;
}
int main()
{
int arr[4] = { 2, 4, 7, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
countPairs(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void countPairs( int arr[],
int N)
{
int countPowerof2 = 0 ;
for ( int i = 0 ; i < N; i++)
{
if (Integer.bitCount(arr[i]) == 1 )
countPowerof2++;
}
int desiredPairs = (countPowerof2 *
(countPowerof2 - 1 )) / 2 ;
System.out.print(desiredPairs + " " );
}
public static void main(String[] args)
{
int arr[] = { 2 , 4 , 7 , 2 };
int N = arr.length;
countPairs(arr, N);
}
}
|
Python3
def countPairs(arr, N):
countPowerof2 = 0
for i in range (N):
if ( bin (arr[i]).count( '1' ) = = 1 ):
countPowerof2 + = 1
desiredPairs = (countPowerof2 *
(countPowerof2 - 1 )) / / 2
print (desiredPairs)
if __name__ = = '__main__' :
arr = [ 2 , 4 , 7 , 2 ]
N = len (arr)
countPairs(arr, N)
|
C#
using System;
using System.Linq;
class GFG{
static void countPairs( int []arr,
int N)
{
int countPowerof2 = 0;
for ( int i = 0; i < N; i++)
{
if ((Convert.ToString(
arr[i], 2)).Count(
f => (f == '1' )) == 1)
countPowerof2++;
}
int desiredPairs = (countPowerof2 *
(countPowerof2 - 1)) / 2;
Console.WriteLine(desiredPairs + " " );
}
public static void Main(String[] args)
{
int []arr = { 2, 4, 7, 2 };
int N = arr.Length;
countPairs(arr, N);
}
}
|
Javascript
<script>
function countPairs(arr,N)
{
let countPowerof2 = 0;
for (let i = 0; i < N; i++)
{
if (Number(arr[i].toString(2).split( "" ).sort().join( "" )).toString().length == 1)
countPowerof2++;
}
let desiredPairs = (countPowerof2 *
(countPowerof2 - 1)) / 2;
document.write(desiredPairs + " " );
}
let arr=[2, 4, 7, 2];
let N = arr.length;
countPairs(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
22 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...