Find if given number is sum of first n natural numbers | java program for finding s such that sum from 1 to s equals to n ; Function to find no . of elements to be added to get s ; Apply Binary search ; Find mid ; find sum of 1 to mid natural numbers using formula ; If sum is equal to n return mid ; If greater than n do r = mid - 1 ; else do l = mid + 1 ; If not possible , return - 1 ; Drivers code
import java . io . * ; public class GFG { static int findS ( int s ) { int l = 1 , r = ( s / 2 ) + 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; int sum = mid * ( mid + 1 ) / 2 ; if ( sum == s ) return mid ; else if ( sum > s ) r = mid - 1 ; else l = mid + 1 ; } return - 1 ; } static public void main ( String [ ] args ) { int s = 15 ; int n = findS ( s ) ; if ( n == - 1 ) System . out . println ( " - 1" ) ; else System . out . println ( n ) ; } }