Range query for count of set bits | 2 - D array that will stored the count of bits set in element of array ; Function store the set bit count in BitCount Array ; traverse over all bits ; mark elements with i 'th bit set ; Check whether the current bit is set or not if it 's  set then mark it. ; store cumulative sum of bits ; Function to process queries ; Driver Code
var BitCount = Array . from ( { length : 10000 } , ( _ , i ) => 0 ) ; function fillSetBitsMatrix ( arr , n ) { for ( i = 0 ; i < 32 ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { var temp = arr [ j ] >> i ; if ( temp % 2 != 0 ) BitCount [ j ] += 1 ; } } for ( i = 1 ; i < n ; i ++ ) BitCount [ i ] += BitCount [ i - 1 ] ; } function Query ( Q , q ) { for ( i = 0 ; i < q ; i ++ ) document . write ( ( BitCount [ Q [ i ] [ 1 ] ] - BitCount [ Q [ i ] [ 0 ] - 1 ] ) + " " ) ; } var Arr = [ 1 , 5 , 6 , 10 , 9 , 4 , 67 ] ; var n = Arr . length ; fillSetBitsMatrix ( Arr , n ) ; var q = 2 ; var Q = [ [ 1 , 5 ] , [ 2 , 6 ] ] ; Query ( Q , q ) ;