Find if given number is sum of first n natural numbers | Java program for above implementation ; 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
class GFG { static int findS ( int s ) { int sum = 0 ; for ( int n = 1 ; sum < s ; n ++ ) { sum += n ; if ( sum == s ) return n ; } return - 1 ; } public static void main ( String [ ] args ) { int s = 15 ; int n = findS ( s ) ; if ( n == - 1 ) System . out . println ( " - 1" ) ; else System . out . println ( n ) ; } }