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
< ? php function findS ( $ s ) { $ l = 1 ; $ r = 1 + ( int ) $ s / 2 ; while ( $ l <= $ r ) { $ mid = ( int ) ( ( $ l + $ r ) / 2 ) ; $ sum = ( int ) ( $ mid * ( $ mid + 1 ) / 2 ) ; if ( $ sum == $ s ) return $ mid ; else if ( $ sum > $ s ) $ r = $ mid - 1 ; else $ l = $ mid + 1 ; } return -1 ; } $ s = 15 ; $ n = findS ( $ s ) ; if ( $ n == -1 ) echo " - 1" ; else echo $ n ; ? >