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
def findS ( s ) : NEW_LINE INDENT l = 1 NEW_LINE r = int ( s / 2 ) + 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = int ( ( l + r ) / 2 ) NEW_LINE sum = int ( mid * ( mid + 1 ) / 2 ) NEW_LINE if ( sum == s ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( sum > s ) : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT s = 15 NEW_LINE n = findS ( s ) NEW_LINE if ( n == - 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT