# Count unordered pairs (i,j) such that product of a[i] and a[j] is power of two in C++

We are given with an array of N elements. The goal is to find the count of all pairs (Arr[i],Arr[j]) which have a sum which is a perfect square such that i!=j. That is Arr[i]+Arr[j] is a perfect square.

We will do this by calculating the sum of pairs and check if the square root of that sum is equal to the floor value of the square root. sqrt(Arr[i]+Arr[j])-floor( sqrt(Arr[i]+Arr[j] )==0.

Let’s understand with examples.

Input − Arr[]= { 4,3,2,1,2,4 } N=6

Output − Count of pairs with sum as perfect square − 2

Explanation

Arr[1]+Arr[3]=4, sqrt(4)-floor(4)=0 4 is a perfect square.
Arr[2]+Arr[4]=4, sqrt(4)-floor(4)=0 4 is a perfect square.
Rest all pairs have sum 7,6,5,8 which are not perfect squares.

Input − Arr[]= { 3,3,3,3,3} N=5

Output − Count of pairs with sum as perfect square − 0

Explanation − All pairs have sum=6, which is not a perfect square.

## Approach used in the below program is as follows

• We take an integer array Arr[] initialized with random numbers.

• Take a variable n which stores the length of Arr[].

• Function countPairs(int arr[], int n) takes an array, its length as input and returns the pairs which have sum which is a perfect square.

• Traverse array using two for loops for each element of the pair.

• Outer Loop from 0<=i<n-1, inner loop i<j<n

• Calculate sum of arr[i], arr[j] are positive.

• Calculate square root of sum as sqrt(sum).

• Now check if sqr-floor(sqr)==0. Which means sum is a perfect square. If true increment count.

• At the end of all loops count will have a total number of pairs that have sum which is perfect square.

• Return the count as result.

## Example

Live Demo

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int countPairs(int arr[], int n){
int count=0;
int prod=0;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
prod=arr[i]*arr[j];
if( ceil(log2(prod))==floor(log2(prod)) ){
count++;
//cout<<endl<<"a :"<<arr[i]<<" b :"<<arr[j]; //to print
}
}
}
return count;
}
int main(){
int arr[] = { 2, 5, 8, 16, 128 };
int n = sizeof(arr) / sizeof(arr[0]);
cout <<endl<<"Pairs whose product is power of 2:"<<countPairs(arr, n);
return 0;
}

## Output

If we run the above code it will generate the following output −

Pairs whose product is power of 2:6

Updated on: 29-Aug-2020

228 Views