Find if given number is sum of first n natural numbers | Function to find no . of elements to be added to get s ; Apply Binary search ; Find mid ; find sum of 1 to mid natural numbers using formula ; If sum is equal to n return mid ; If greater than n do r = mid - 1 ; else do l = mid + 1 ; If not possible , return - 1 ; Drivers code
function findS ( s ) { var l = 1 , r = parseInt ( ( s / 2 ) + 1 ) ; while ( l <= r ) { var mid = parseInt ( ( l + r ) / 2 ) ; var sum = mid * parseInt ( ( mid + 1 ) / 2 ) ; if ( sum == s ) return mid ; else if ( sum > s ) r = mid - 1 ; else l = mid + 1 ; } return - 1 ; } var s = 15 ; var n = findS ( s ) ; if ( n == - 1 ) document . write ( " " ) ; else document . write ( n ) ;