Number of pairs whose sum is a power of 2 | Set 2
Last Updated :
18 Jan, 2023
Given an array arr[] consisting of N integers, the task is to count the maximum number of pairs (arr[i], arr[j]) such that arr[i] + arr[j] is a power of 2.
Examples:
Input: arr[] = {1, -1, 2, 3}
Output: 5
Explanation: (1, 1), (2, 2), (1, 3), (-1, 3), (-1, 2) are the valid pairs whose sum is power of 2.
Input: arr[] = {1, 1, 1}
Output: 6
Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from a given array and for each pair, check if the sum of the pair is a power of 2 or not.
C++
#include <bits/stdc++.h>
using namespace std;
#include <bits/stdc++.h>
using namespace std;
int countPair(vector< int >& arr, int k)
{
int count = 0;
for ( int i = 0; i < arr.size(); ++i) {
int sum = 0;
for ( int j = i; j < arr.size(); j++) {
int sum = arr[i] + arr[j];
int t = log2(sum);
if ( pow (2, t) == sum) {
count++;
}
}
}
return count;
}
int main()
{
vector< int > arr = { 1, 8, 2, 10, 6 };
int n = arr.size();
cout << countPair(arr, n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int countPair( int [] arr, int k)
{
int count = 0 ;
for ( int i = 0 ; i < arr.length; ++i) {
for ( int j = i; j < arr.length; j++) {
int sum = arr[i] + arr[j];
int t = ( int )(Math.log(sum) / Math.log( 2 ));
if (Math.pow( 2 , t) == sum) {
count++;
}
}
}
return count;
}
public static void main (String[] args) {
int [] arr = { 1 , 8 , 2 , 10 , 6 };
int n = arr.length;
System.out.println(countPair(arr, n));
}
}
|
Python3
import math
def countPair(arr, k):
count = 0 ;
for i in range ( 0 , len (arr)):
ans = 0 ;
for j in range (i, len (arr)):
ans = arr[i] + arr[j];
t = math.floor(math.log2(ans));
if (math. pow ( 2 , t) = = ans):
count + = 1 ;
return count;
arr = [ 1 , 8 , 2 , 10 , 6 ];
n = len (arr);
print (countPair(arr, n))
|
C#
using System;
class GFG
{
static int CountPair( int [] arr)
{
int count = 0;
for ( int i = 0; i < arr.Length; ++i)
{
for ( int j = i; j < arr.Length; j++)
{
int sum = arr[i] + arr[j];
int t = ( int )(Math.Log(sum) / Math.Log(2));
if (Math.Pow(2, t) == sum)
{
count++;
}
}
}
return count;
}
public static void Main ( string [] args)
{
int [] arr = { 1, 8, 2, 10, 6 };
int n = arr.Length;
Console.WriteLine(CountPair(arr));
}
}
|
Javascript
function countPair(arr, k)
{
let count = 0;
for (let i = 0; i < arr.length; ++i) {
let sum = 0;
for (let j = i; j < arr.length; j++) {
let sum = arr[i] + arr[j];
let t = Math.floor(Math.log2(sum));
if (Math.pow(2, t) == sum) {
count++;
}
}
}
return count;
}
let arr = [ 1, 8, 2, 10, 6 ];
let n = arr.length;
console.log(countPair(arr, n));
|
Time Complexity: O(N2*log(Max)), where N is the length of the given array and Max is the maximum possible value of any pair during their summation.
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using HashMap. Follow the steps below to solve the problem:
- Create a Map to store frequency of each element of the array arr[].
- Initialize a variable ans to store the count of pairs with sum equal to any power of 2.
- Traverse the range [0, 31] and generate all the powers of 2, i.e. 20 to 231.
- Traverse the given array for every power of 2 generated and check if map[key – arr[j]] exists or not, where key is equal to 2i.
- If found to be true, increase count by map[key – arr[j]], as pair(s) (arr[j], key – arr[j]) exists with sum equal to a power of 2.
- Finally, print count / 2 as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countPair( int arr[], int n)
{
map< int , int > m;
for ( int i = 0; i < n; i++)
m[arr[i]]++;
int ans = 0;
for ( int i = 0; i < 31; i++) {
int key = pow (2, i);
for ( int j = 0; j < n; j++) {
int k = key - arr[j];
if (m.find(k) == m.end())
continue ;
else
ans += m[k];
if (k == arr[j])
ans++;
}
}
return ans / 2;
}
int main()
{
int arr[] = { 1, 8, 2, 10, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countPair(arr, n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int countPair( int [] arr, int n)
{
Map<Integer, Integer> m
= new HashMap<>();
for ( int i = 0 ; i < n; i++)
m.put(arr[i], m.getOrDefault(
arr[i], 0 )
+ 1 );
int ans = 0 ;
for ( int i = 0 ; i < 31 ; i++) {
int key = ( int )Math.pow( 2 , i);
for ( int j = 0 ; j < arr.length;
j++) {
int k = key - arr[j];
ans += m.getOrDefault(k, 0 );
if (k == arr[j])
ans++;
}
}
return ans / 2 ;
}
public static void main(String[] args)
{
int [] arr = { 1 , - 1 , 2 , 3 };
int n = arr.length;
System.out.println(countPair(arr, n));
}
}
|
Python3
from math import pow
def countPair(arr, n):
m = {}
for i in range (n):
m[arr[i]] = m.get(arr[i], 0 ) + 1
ans = 0
for i in range ( 31 ):
key = int ( pow ( 2 , i))
for j in range (n):
k = key - arr[j]
if k not in m:
continue
else :
ans + = m.get(k, 0 )
if (k = = arr[j]):
ans + = 1
return ans / / 2
if __name__ = = '__main__' :
arr = [ 1 , 8 , 2 , 10 , 6 ]
n = len (arr)
print (countPair(arr, n))
|
Javascript
<script>
function countPair(arr, n)
{
var m= new Map();
for ( var i = 0; i < n; i++)
{
if (m.has(arr[i]))
m.set(arr[i], m.get(arr[i])+1)
else
m.set(arr[i], 1)
}
var ans = 0;
for ( var i = 0; i < 31; i++) {
var key = Math.pow(2, i);
for ( var j = 0; j < n; j++) {
var k = key - arr[j];
if (!m.has(k))
continue ;
else
ans += m.get(k);
if (k == arr[j])
ans++;
}
}
return ans / 2;
}
var arr = [1, 8, 2, 10, 6]
var n = arr.length
document.write( countPair(arr, n));
</script>
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static int countPair( int [] arr, int n)
{
Dictionary< int , int > map
= new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
if (!map.ContainsKey(arr[i])) {
map[arr[i]] = 0;
}
map[arr[i]] = map[arr[i]] + 1;
}
int ans = 0;
for ( int i = 0; i < 31; i++) {
int key = 1 << i;
for ( int j = 0; j < n; j++) {
int k = key - arr[j];
if (!map.ContainsKey(k)) {
continue ;
}
else {
ans += map[k];
}
if (k == arr[j]) {
ans++;
}
}
}
return ans / 2;
}
public static void Main(String[] args)
{
int [] arr = { 1, 8, 2, 10, 6 };
int n = arr.Length;
Console.WriteLine(countPair(arr, n));
}
}
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N). We are using a map to store elements
Share your thoughts in the comments
Please Login to comment...