text: Count 1 s present in a range of indices [ L , R ] in a given array | Function to find the size of the array if the array initially contains a single element ; Base case ; P / 2 -> findSize ( N 2 ) P % 2 -> 1 P / 2 -> findSize ( N / 2 ) ; Function to return the count of 1 s in the range [ L , R ] ; Base Case ; PART 1 -> N / 2 [ 1 , Siz_M ] ; Update the right end point of the range to min ( Siz_M , R ) ; PART 2 -> N % 2 [ SizM + 1 , Siz_M + 1 ] ; PART 3 -> N / 2 [ SizM + 2 , 2 * Siz_M - 1 ] Same as PART 1 Property of Symmetricity Shift the coordinates according to PART 1 Subtract ( Siz_M + 1 ) from both L , R ; Driver Code ; Input ; Counts the number of 1 's in  the range [L, R]
code: def findSize ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT Size = 2 * findSize ( N // 2 ) + 1 NEW_LINE return Size NEW_LINE DEDENT def CountOnes ( N , L , R ) : NEW_LINE INDENT if ( L > R ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( N <= 1 ) : NEW_LINE INDENT return N NEW_LINE DEDENT ret = 0 NEW_LINE M = N // 2 NEW_LINE Siz_M = findSize ( M ) NEW_LINE if ( L <= Siz_M ) : NEW_LINE INDENT ret += CountOnes ( N // 2 , L , min ( Siz_M , R ) ) NEW_LINE DEDENT if ( L <= Siz_M + 1 and Siz_M + 1 <= R ) : NEW_LINE INDENT ret += N % 2 NEW_LINE DEDENT if ( Siz_M + 1 < R ) : NEW_LINE INDENT ret += CountOnes ( N // 2 , max ( 1 , L - Siz_M - 1 ) , R - Siz_M - 1 ) NEW_LINE DEDENT return ret NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE L = 2 NEW_LINE R = 5 NEW_LINE print ( CountOnes ( N , L , R ) ) NEW_LINE DEDENT