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 sum of first i natural numbers ; Stores the result ; Iterate over the range [ 1 , N ] ; Increment sum by i ; Is sum is less than or equal to K ; Otherwise , ; Return res ; Input ; Function call
function Count ( N , K ) { if ( K == 0 ) return 0 ; let sum = 0 ; let res = 0 ; for ( let i = 1 ; i <= N ; i ++ ) { sum += i ; if ( sum <= K ) res ++ ; else break ; } return res ; } let N = 6 , K = 14 ; document . write ( Count ( N , K ) ) ;