Find if given number is sum of first n natural numbers | Java 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
import java . util . * ; class GFG { public static int isvalid ( int s ) { double k = ( - 1.0 + Math . sqrt ( 1 + 8 * s ) ) / 2 ; if ( Math . ceil ( k ) == Math . floor ( k ) ) return ( int ) k ; else return - 1 ; } public static void main ( String [ ] args ) { int s = 15 ; System . out . print ( isvalid ( s ) ) ; } }