Number of days after which tank will become empty | Utility method to get sum of first n numbers ; Method returns minimum number of days after which tank will become empty ; If water filling is more than capacity then after C days only tank will become empty ; Initialize binary search variable ; Loop until low is less than high ; If cumulate sum is greater than ( C - l ) then search on left side ; If ( C - l ) is more then search on right side ; Final answer will be obtained by adding l to binary search result ; Driver code
function getCumulateSum ( n ) { return parseInt ( ( n * ( n + 1 ) ) / 2 , 10 ) ; } function minDaysToEmpty ( C , l ) { if ( C <= l ) return C ; let lo = 0 ; let hi = 1e4 ; let mid ; while ( lo < hi ) { mid = parseInt ( ( lo + hi ) / 2 , 10 ) ; if ( getCumulateSum ( mid ) >= ( C - l ) ) hi = mid ; else lo = mid + 1 ; } return ( l + lo ) ; } let C = 5 ; let l = 2 ; document . write ( minDaysToEmpty ( C , l ) ) ;