B. Powers of Two
You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer xexists so that ai + aj = 2x).
Input
The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers.
The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.
Examples
input
4 7 3 2 1
output
2
input
3 1 1 1
output
3
[Analysis]: After reading the question carefully, it is found that ai will not exceed 10^9, which is approximately equal to 2^30, so we can first type out a table of 2^k, and then for ai, subtract ai from 2^k, Use binary search to get the number of aj, and accumulate the result. The time complexity is O(N).
【Code】:
#include<bits/stdc++.h> using namespace std; #define ll long long #define maxn 100010 ll a[maxn]; int n; /* Given an array, find the number of pairs where ai + aj is a power of 2 */ int main() { while(cin >> n){ ll ans = 0; for(int i=0; i<n; i++) cin >> a[i]; sort(a,a+n); for(ll i=0; i<n; i++){ for(ll j=0; j<32; j++){ ll t = (1<<j) - a[i]; ans += upper_bound(a+i+1,a+n,t)-lower_bound(a+i+1,a+n,t); } } cout << ans << endl; } return 0; }