Smallest value of N such that the sum of all natural numbers from K to N is at least X | Function to check if the sum of natural numbers from K to N is >= X ; Function to find the minimum value of N such that the sum of natural numbers from K to N is at least X ; If K is greater than X ; Perform the Binary Search ; If the sum of the natural numbers from K to mid is atleast X ; Update res ; Update high ; Otherwise , update low ; Print the value of res as the answer ; Driver Code
function isGreaterEqual ( N , K , X ) { return ( ( N * parseInt ( ( N + 1 ) / 2 ) ) - ( ( K - 1 ) * parseInt ( K / 2 ) ) ) >= X ; } function minimumNumber ( K , X ) { if ( K > X ) { document . write ( " " ) ; return ; } let low = K , high = X , res = - 1 ; while ( low <= high ) { let mid = low + parseInt ( ( high - low ) / 2 ) ; if ( isGreaterEqual ( mid , K , X ) ) { res = mid ; high = mid - 1 ; } else low = mid + 1 ; } document . write ( res ) ; } let K = 5 , X = 13 ; minimumNumber ( K , X ) ;