Smallest value of N such that the sum of all natural numbers from K to N is at least X | C ++ program for the above approach ; Function to check if the sum of natural numbers from K to N is >= X ; Function to find the minimum value of N such that the sum of natural numbers from K to N is at least X ; If K is greater than X ; Perform the Binary Search ; If the sum of the natural numbers from K to mid is atleast X ; Update res ; Update high ; Otherwise , update low ; Print the value of res as the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isGreaterEqual ( int N , int K , int X ) { return ( ( N * 1LL * ( N + 1 ) / 2 ) - ( ( K - 1 ) * 1LL * K / 2 ) ) >= X ; } void minimumNumber ( int K , int X ) { if ( K > X ) { cout << " - 1" ; return ; } int low = K , high = X , res = -1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( isGreaterEqual ( mid , K , X ) ) { res = mid ; high = mid - 1 ; } else low = mid + 1 ; } cout << res ; } int main ( ) { int K = 5 , X = 13 ; minimumNumber ( K , X ) ; return 0 ; }