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
function findS ( s ) { var sum = 0 ; for ( n = 1 ; sum < s ; n ++ ) { sum += n ; if ( sum == s ) return n ; } return - 1 ; } var s = 15 ; var n = findS ( s ) ; if ( n == - 1 ) document . write ( " " ) ; else document . write ( n ) ;