 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of pairs whose sum is a power of 2 in C++
Given an array, we have to find the number of pairs whose sum is a power of 2. Let's see the example.
Input
arr = [1, 2, 3]
Output
1
There is only one pair whose sum is a power of 2. And the pair is (1, 3).
Algorithm
- Initialise array with random numbers.
- Initialise the count to 0.
- Write two loops to get all the pairs of the array.- Compute the sum of every pair.
- Check whether the sum is a power of 2 or not using bitwise AND.
- Increment the count if the count is a power of 2.
 
- Return the count.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; int get2PowersCount(int arr[], int n) {    int count = 0;    for (int i = 0; i < n; i++) {       for (int j = i + 1; j < n; j++) {          int sum = arr[i] + arr[j];          if ((sum & (sum - 1)) == 0) {             count++;          }       }    }    return count; } int main() {    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };    int n = 10;    cout << get2PowersCount(arr, n) << endl;    return 0; } Output
If you run the above code, then you will get the following result.
6
Advertisements
 