text: Find the sum of all array elements that are equidistant from two consecutive powers of 2 | C ++ program for the above approach ; Function to print the sum of array elements that are equidistant from two consecutive powers of 2 ; Stores the resultant sum of the array elements ; Traverse the array arr [ ] ; Stores the power of 2 of the number arr [ i ] ; Stores the number which is power of 2 and lesser than or equal to arr [ i ] ; Stores the number which is power of 2 and greater than or equal to arr [ i ] ; If arr [ i ] - LesserValue is the same as LargerValue - arr [ i ] ; Increment res by arr [ i ] ; Return the resultant sum res ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int FindSum ( int arr [ ] , int N ) { int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int power = log2 ( arr [ i ] ) ; int LesserValue = pow ( 2 , power ) ; int LargerValue = pow ( 2 , power + 1 ) ; if ( ( arr [ i ] - LesserValue ) == ( LargerValue - arr [ i ] ) ) { res += arr [ i ] ; } } return res ; } int main ( ) { int arr [ ] = { 10 , 24 , 17 , 3 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << FindSum ( arr , N ) ; return 0 ; }