Find if given number is sum of first n natural numbers | C ++ program of the above approach ; Function to check if the s is the sum of first N natural number ; Solution of Quadratic Equation ; Condition to check if the solution is a integer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE # define ll  long long NEW_LINE using namespace std ; ll int isvalid ( ll int s ) { float k = ( -1 + sqrt ( 1 + 8 * s ) ) / 2 ; if ( ceil ( k ) == floor ( k ) ) return k ; else return -1 ; } int main ( ) { int s = 15 ; cout << isvalid ( s ) ; return 0 ; }