Find the sum of all array elements that are equidistant from two consecutive powers of 2 | Python3 program for the above approach ; Function to prthe 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
from math import log2 NEW_LINE def FindSum ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT power = int ( log2 ( arr [ i ] ) ) NEW_LINE LesserValue = pow ( 2 , power ) NEW_LINE LargerValue = pow ( 2 , power + 1 ) NEW_LINE if ( ( arr [ i ] - LesserValue ) == ( LargerValue - arr [ i ] ) ) : NEW_LINE INDENT res += arr [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 24 , 17 , 3 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( FindSum ( arr , N ) ) NEW_LINE DEDENT