Find the smallest value of N such that sum of first N natural numbers is â ‰¥ X |  ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isGreaterEqual ( int N , int X ) { return ( N * 1LL * ( N + 1 ) / 2 ) >= X ; } 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 ; } int main ( ) { int X = 14 ; cout << minimumPossible ( X ) ; return 0 ; }