Find if given number is sum of first n natural numbers | C # 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
using System ; 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 ( ) { int s = 15 ; int n = findS ( s ) ; if ( n == - 1 ) Console . WriteLine ( " - 1" ) ; else Console . WriteLine ( n ) ; } }