Maximize X such that sum of numbers in range [ 1 , X ] is at most K | Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores the result ; Iterate until low is less than or equal to high ; Stores the sum of first mid natural numbers ; If sum is less than or equal to K ; Update res and low ; Otherwise , ; Update ; Return res ; Input ; Function call
function Count ( N , K ) { if ( K == 0 ) return 0 ; var res = 0 ; var low = 2 , high = N ; while ( low <= high ) { var mid = ( low + high ) / 2 ; var sum = ( mid * mid + mid ) / 2 ; if ( sum <= K ) { res = Math . max ( res , mid ) ; low = mid + 1 ; } else { high = mid - 1 ; } } return res ; } var N = 6 , K = 14 ; document . write ( Count ( N , K ) ) ;