Count of elements which are power of 2 in a given range subarray for Q queries | Python3 implementation to find elements that are a power of two ; prefix [ i ] is going to store the number of elements which are a power of two till i ( including i ) . ; Function to find the maximum range whose sum is divisible by M . ; Calculate the prefix sum ; Function to return the number of elements which are a power of two in a subarray ; Driver code
MAX = 10000 NEW_LINE prefix = [ 0 ] * ( MAX + 1 ) NEW_LINE def isPowerOfTwo ( x ) : NEW_LINE INDENT if ( x and ( not ( x & ( x - 1 ) ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def computePrefix ( n , a ) : NEW_LINE INDENT if ( isPowerOfTwo ( a [ 0 ] ) ) : NEW_LINE INDENT prefix [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] NEW_LINE if ( isPowerOfTwo ( a [ i ] ) ) : NEW_LINE INDENT prefix [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def query ( L , R ) : NEW_LINE INDENT return prefix [ R ] - prefix [ L - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 3 , 8 , 5 , 2 , 5 , 10 ] NEW_LINE N = len ( A ) NEW_LINE Q = 2 NEW_LINE computePrefix ( N , A ) NEW_LINE print ( query ( 0 , 4 ) ) NEW_LINE print ( query ( 3 , 5 ) ) NEW_LINE DEDENT