
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N) in C++
- Count number of distinct pairs whose sum exists in the given array in C++
- Program to count number of fraction pairs whose sum is 1 in python
- Count of pairs in an array whose sum is a perfect square in C++
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Number of pairs with maximum sum in C++
- Program to count indices pairs for which elements sum is power of 2 in Python
- Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N) in C++
- How to find all pairs of elements in Java array whose sum is equal to a given number?
- Find M-th number whose repeated sum of digits of a number is N in C++
- Count pairs in array whose sum is divisible by 4 in C++
- Count pairs in array whose sum is divisible by K in C++
- Count pairs in a sorted array whose sum is less than x in C++
- n-th number whose sum of digits is ten in C++
- Count all pairs of adjacent nodes whose XOR is an odd number in C++

Advertisements