- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- 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

# Program to count indices pairs for which elements sum is power of 2 in Python

Suppose we have a list of numbers called nums. We have to find the number of index pairs i, j, where i < j such that nums[i] + nums[j] is equal to 2^k for some 0 >= k.

So, if the input is like nums = [1, 2, 6, 3, 5], then the output will be 3, as there are three pairs sum like (6, 2): sum is 8, (5, 3): sum is 8 and (1, 3) sum is 4

To solve this, we will follow these steps −

res := 0

c := a map containing frequencies of each elements present in

for each x in nums, do

for j in range 0 to 31, do

res := res + c[(2^j) - x]

c[x] := c[x] + 1

return res

## Example

Let us see the following implementation to get better understanding

from collections import Counter def solve(nums): res, c = 0, Counter() for x in nums: for j in range(32): res += c[(1 << j) - x] c[x] += 1 return res nums = [1, 2, 6, 3, 5] print(solve(nums))

## Input

[1, 2, 6, 3, 5]

## Output

3

- Related Questions & Answers
- Program to count index pairs for which array elements are same in Python
- Python program to count pairs for consecutive elements
- Number of pairs whose sum is a power of 2 in C++
- Program to count number of fraction pairs whose sum is 1 in python
- Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N) in C++
- Maximum count of pairs which generate the same sum in C++
- Program to find Reordered Power of 2 in Python
- Program to find sum of the 2 power sum of all subarray sums of a given array in Python
- Count of numbers which can be made power of 2 by given operation in C++
- C/C++ Program to Find sum of Series with n-th term as n power of 2 - (n-1) power of 2
- Python Program to repeat elements at custom indices
- Python program to count the pairs of reverse strings
- Python program to count Bidirectional Tuple Pairs
- Program to count number of valid pairs from a list of numbers, where pair sum is odd in Python
- Python program to remove elements at Indices in List

Advertisements