Count of elements which cannot form any pair whose sum is power of 2

Given an array arr[] of length N, the task is to print the number of array elements that cannot form a pair with any other array element whose sum is a power of two.
Examples: 

Input: arr[] = {6, 2, 11} 
Output:
Explanation: 
Since 6 and 2 can form a pair with sum 8 (= 23). So only 11 has to be removed as it does not form a sum which is a power of 2. 
Input: arr[] = [1, 1, 1, 1023], 
Output:
Explanation: 
The given array elements can be split into following two pairs: 
(1, 1) with sum 2(= 21
(1, 1023) with sum 1024(= 210
Hence, no need to remove any element. 
 

Approach: 
To solve the problem mentioned above, follow the steps below: 

  • Store the frequencies of all array elements in a Map.
  • For every array element a[i], iterate over all possible sums p = {20, 21, …., 230} and check if p – a[i] is present in the array or not.
  • Either of the following two conditions needs to be satisfied: 
    1. Let s = p – a[i]. If s is present in the array more than once, then a pair consisting of a[i] with sum p is possible.
    2. If s is present only once in the array, then s has to be different from a[i] for a possible pair.
    3. If none of the above two conditions are satisfied, no pair consisting of a[i] is possible with sum p.
  • If the above two conditions do not satisfy for any p for the current a[i], then increase the count as a[i] cannot form a sum which is a power of 2 with any other array element.
  • Print the final value of count.

Below is the implementation of the above approach: 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to count of
// array elements which do
// not form a pair with sum
// equal to a power of 2
// with any other array element
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate
// and return the
// count of elements
 
int powerOfTwo(int a[], int n)
{
    // Stores the frequencies
    // of every array element
 
    map<int, int> mp;
 
    for (int i = 0; i < n; i++)
        mp[a[i]]++;
 
    // Stores the count
    // of removals
 
    int count = 0;
 
    for (int i = 0; i < n; i++) {
        bool f = false;
 
        // For every element, check if
        // it can form a sum equal to
        // any power of 2 with any other
        // element
 
        for (int j = 0; j < 31; j++) {
 
            // Store pow(2, j) - a[i]
            int s = (1 << j) - a[i];
 
            // Check if s is present
            // in the array
            if (mp.count(s)
 
                // If frequency of s
                // exceeds 1
                && (mp[s] > 1
 
                    // If s has frequency 1
                    // but is different from
                    // a[i]
                    || mp[s] == 1 && s != a[i]))
 
                // Pair possible
                f = true;
        }
 
        // If no pair possible for
        // the current element
 
        if (f == false)
            count++;
    }
 
    // Return the answer
    return count;
}
 
// Driver Code
int main()
{
    int a[] = { 6, 2, 11 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << powerOfTwo(a, n);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count of array
// elements which do not form a
// pair with sum equal to a power
// of 2 with any other array element
import java.util.*;
 
class GFG{
 
// Function to calculate and return
// the count of elements
static int powerOfTwo(int a[], int n)
{
     
    // Stores the frequencies
    // of every array element
    HashMap<Integer,
            Integer> mp = new HashMap<Integer,
                                      Integer>();
 
    for(int i = 0; i < n; i++)
    {
       if(mp.containsKey(a[i]))
       {
           mp.put(a[i], mp.get(a[i]) + 1);
       }
       else
       {
           mp.put(a[i], 1);
       }
    }
     
    // Stores the count
    // of removals
    int count = 0;
 
    for(int i = 0; i < n; i++)
    {
       boolean f = false;
        
       // For every element, check if
       // it can form a sum equal to
       // any power of 2 with any other
       // element
       for(int j = 0; j < 31; j++)
       {
           
          // Store Math.pow(2, j) - a[i]
          int s = (1 << j) - a[i];
           
          // Check if s is present
          // in the array
          if (mp.containsKey(s) &&
              
             // If frequency of s
             // exceeds 1
             (mp.get(s) > 1 ||
              
              // If s has frequency 1
              // but is different from
              // a[i]
              mp.get(s) == 1 && s != a[i]))
              
             // Pair possible
             f = true;
       }
        
       // If no pair possible for
       // the current element
       if (f == false)
           count++;
    }
     
    // Return the answer
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = { 6, 2, 11 };
    int n = a.length;
     
    System.out.print(powerOfTwo(a, n));
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count of
# array elements which do
# not form a pair with sum
# equal to a power of 2
# with any other array element
from collections import defaultdict
 
# Function to calculate
# and return the
# count of elements
def powerOfTwo(a, n):
 
    # Stores the frequencies
    # of every array element
    mp = defaultdict (int)
 
    for i in range (n):
        mp[a[i]] += 1
 
    # Stores the count
    # of removals
    count = 0
 
    for i in range (n):
        f = False
 
        # For every element, check if
        # it can form a sum equal to
        # any power of 2 with any other
        # element
 
        for j in range (31):
 
            # Store pow(2, j) - a[i]
            s = (1 << j) - a[i]
 
            # Check if s is present
            # in the array
            if (s in mp
 
                # If frequency of s
                # exceeds 1
                and (mp[s] > 1
 
                    # If s has frequency 1
                    # but is different from
                    # a[i]
                    or mp[s] == 1 and
                       s != a[i])):
 
                # Pair possible
                f = True
 
        # If no pair possible for
        # the current element
        if (f == False):
            count += 1
   
    # Return the answer
    return count
 
# Driver Code
if __name__ == "__main__":
   
    a = [6, 2, 11]
    n = len(a)
    print(powerOfTwo(a, n))
 
# This code is contributed by Chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count of array
// elements which do not form a
// pair with sum equal to a power
// of 2 with any other array element
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to calculate and return
// the count of elements
static int powerOfTwo(int []a, int n)
{
     
    // Stores the frequencies
    // of every array element
    Dictionary<int,
               int> mp = new Dictionary<int,
                                        int>();
 
    for(int i = 0; i < n; i++)
    {
        if(mp.ContainsKey(a[i]))
        {
            mp[a[i]] = mp[a[i]] + 1;
        }
        else
        {
            mp.Add(a[i], 1);
        }
    }
     
    // Stores the count
    // of removals
    int count = 0;
 
    for(int i = 0; i < n; i++)
    {
        bool f = false;
         
        // For every element, check if
        // it can form a sum equal to
        // any power of 2 with any other
        // element
        for(int j = 0; j < 31; j++)
        {
         
            // Store Math.Pow(2, j) - a[i]
            int s = (1 << j) - a[i];
             
            // Check if s is present
            // in the array
            if (mp.ContainsKey(s) &&
                 
                // If frequency of s
                // exceeds 1
                (mp[s] > 1 ||
                 
                // If s has frequency 1
                // but is different from
                // a[i]
                mp[s] == 1 && s != a[i]))
                 
                // Pair possible
                f = true;
        }
         
        // If no pair possible for
        // the current element
        if (f == false)
            count++;
    }
     
    // Return the answer
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []a = { 6, 2, 11 };
    int n = a.Length;
     
    Console.Write(powerOfTwo(a, n));
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

1


 

Time Complexity: O(N) 
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.