Find the smallest value of N such that sum of first N natural numbers is â ‰¥ X | Java program for the above approach ; Function to check if sum of first N natural numbers is >= X ; Finds minimum value of N such that sum of first N natural number >= X ; Binary Search ; Checks if sum of first ' mid ' natural numbers is greater than equal to X ; Update res ; Update high ; Update low ; Driver Code ; Input ; Finds minimum value of N such that sum of first N natural number >= X
import java . util . * ; class GFG { static boolean isGreaterEqual ( int N , int X ) { return ( N * ( N + 1 ) / 2 ) >= X ; } static int minimumPossible ( int X ) { int low = 1 , high = X , res = - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( isGreaterEqual ( mid , X ) ) { res = mid ; high = mid - 1 ; } else low = mid + 1 ; } return res ; } public static void main ( String [ ] args ) { int X = 14 ; System . out . print ( minimumPossible ( X ) ) ; } }