Find if given number is sum of first n natural numbers | Function to find no . of elements to be added from 1 to get n ; Start adding numbers from 1 ; If sum becomes equal to s return n ; Drivers code
< ? php function findS ( $ s ) { $ sum = 0 ; for ( $ n = 1 ; $ sum < $ s ; $ n ++ ) { $ sum += $ n ; if ( $ sum == $ s ) return $ n ; } return -1 ; } $ s = 15 ; $ n = findS ( $ s ) ; if ( $ n == -1 ) echo " - 1" ; else echo $ n ; ? >