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
#include <iostream> NEW_LINE using namespace std ; int findS ( int s ) { int sum = 0 ; for ( int n = 1 ; sum < s ; n ++ ) { sum += n ; if ( sum == s ) return n ; } return -1 ; } int main ( ) { int s = 15 ; int n = findS ( s ) ; n == -1 ? cout << " - 1" : cout << n ; return 0 ; }