Smallest value of N such that the sum of all natural numbers from K to N is at least X

Given two positive integers X and K, the task is to find the minimum value of N possible such that the sum of all natural numbers from the range [K, N] is at least X. If no possible value of N exists, then print -1.
Examples:
Input: K = 5, X = 13
Output: 7
Explanation: The minimum possible value is 7. Sum = 5 + 6 + 7 = 18, which is at least 13.Input: K = 3, X = 15
Output: 6
Naive Approach: The simplest approach to solve this problem is to check for every value in the range [K, X] and return the first value from this range which has sum of the first N natural numbers at least X.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the minimum possible// value of N such that sum of natural// numbers from K to N is at least Xvoid minimumNumber(int K, int X){Â Â Â Â // If K is greater than XÂ Â Â Â if (K > X) {Â Â Â Â Â Â Â Â cout << "-1";Â Â Â Â Â Â Â Â return;Â Â Â Â }Â
    // Stores value of minimum N    int ans = 0;Â
    // Stores the sum of values    // over the range [K, ans]    int sum = 0;Â
    // Iterate over the range [K, N]    for (int i = K; i <= X; i++) {Â
        sum += i;Â
        // Check if sum of first i        // natural numbers is >= X        if (sum >= X) {            ans = i;            break;        }    }Â
    // Print the possible value of ans    cout << ans;}Â
// Driver Codeint main(){Â Â Â Â int K = 5, X = 13;Â Â Â Â minimumNumber(K, X);Â
    return 0;} |
Java
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*;Â
class GFG{Â
// Function to find the minimum possible// value of N such that sum of natural// numbers from K to N is at least Xstatic void minimumNumber(int K, int X){Â Â Â Â Â Â Â Â Â // If K is greater than XÂ Â Â Â if (K > X) Â Â Â Â {Â Â Â Â Â Â Â Â System.out.println("-1");Â Â Â Â Â Â Â Â return;Â Â Â Â }Â
    // Stores value of minimum N    int ans = 0;Â
    // Stores the sum of values    // over the range [K, ans]    int sum = 0;Â
    // Iterate over the range [K, N]    for(int i = K; i <= X; i++)     {        sum += i;Â
        // Check if sum of first i        // natural numbers is >= X        if (sum >= X)         {            ans = i;            break;        }    }Â
    // Print the possible value of ans    System.out.println(ans);}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int K = 5, X = 13;Â Â Â Â Â Â Â Â Â minimumNumber(K, X);}}Â
// This code is contributed by Kingash |
Python3
# Python3 program for the above approachÂ
# Function to find the minimum possible# value of N such that sum of natural# numbers from K to N is at least Xdef minimumNumber(K, X):Â Â Â Â Â Â Â Â Â # If K is greater than XÂ Â Â Â if (K > X):Â Â Â Â Â Â Â Â print("-1")Â Â Â Â Â Â Â Â returnÂ
    # Stores value of minimum N    ans = 0Â
    # Stores the sum of values    # over the range [K, ans]    sum = 0Â
    # Iterate over the range [K, N]    for i in range(K, X + 1):        sum += iÂ
        # Check if sum of first i        # natural numbers is >= X        if (sum >= X):            ans = i            breakÂ
    # Print the possible value of ans    print(ans)Â
# Driver CodeK = 5X = 13Â
minimumNumber(K, X)Â
# This code is contributed by subham348 |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Function to find the minimum possible// value of N such that sum of natural// numbers from K to N is at least Xstatic void minimumNumber(int K, int X){Â Â Â Â Â Â Â Â Â // If K is greater than XÂ Â Â Â if (K > X) Â Â Â Â {Â Â Â Â Â Â Â Â Console.Write("-1");Â Â Â Â Â Â Â Â return;Â Â Â Â }Â
    // Stores value of minimum N    int ans = 0;Â
    // Stores the sum of values    // over the range [K, ans]    int sum = 0;Â
    // Iterate over the range [K, N]    for(int i = K; i <= X; i++)     {        sum += i;Â
        // Check if sum of first i        // natural numbers is >= X        if (sum >= X)         {            ans = i;            break;        }    }Â
    // Print the possible value of ans    Console.Write(ans);}Â
// Driver Codepublic static void Main(){Â Â Â Â int K = 5, X = 13;Â
    minimumNumber(K, X);}}Â
// This code is contributed by sanjoy_62 |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Function to find the minimum possible// value of N such that sum of natural// numbers from K to N is at least Xfunction minimumNumber(K, X){Â Â Â Â // If K is greater than XÂ Â Â Â if (K > X) {Â Â Â Â Â Â Â Â document.write("-1");Â Â Â Â Â Â Â Â return;Â Â Â Â }Â
    // Stores value of minimum N    let ans = 0;Â
    // Stores the sum of values    // over the range [K, ans]    let sum = 0;Â
    // Iterate over the range [K, N]    for (let i = K; i <= X; i++) {Â
        sum += i;Â
        // Check if sum of first i        // natural numbers is >= X        if (sum >= X) {            ans = i;            break;        }    }Â
    // Print the possible value of ans    document.write(ans);}Â
// Driver Code    let K = 5, X = 13;    minimumNumber(K, X);Â
// This code is contributed by Surbhi Tyagi.Â
</script> |
7
Â
Time Complexity: O(N – K)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using Binary Search. Follow the steps below to solve the given problem:
- Initialize a variable, say res as -1, to store the smallest possible value of N that satisfies the given conditions.
- Initialize two variables, say low as K, and high as X, and perform Binary Search on this range by performing the following steps:
- Find the value of mid as low + (high – low) / 2.
- If the sum of natural numbers from K to mid is greater than or equal to X or not.
- If found to be true, then update res as mid and set high = (mid – 1). Otherwise, update the low to (mid + 1).
- After completing the above steps, print the value of res as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to check if the sum of// natural numbers from K to N is >= Xbool isGreaterEqual(int N, int K, int X){Â Â Â Â return ((N * 1LL * (N + 1) / 2)Â Â Â Â Â Â Â Â Â Â Â Â - ((K - 1) * 1LL * K / 2))Â Â Â Â Â Â Â Â Â Â Â >= X;}Â
// Function to find the minimum value// of N such that the sum of natural// numbers from K to N is at least Xvoid minimumNumber(int K, int X){Â Â Â Â // If K is greater than XÂ Â Â Â if (K > X) {Â Â Â Â Â Â Â Â cout << "-1";Â Â Â Â Â Â Â Â return;Â Â Â Â }Â
    int low = K, high = X, res = -1;Â
    // Perform the Binary Search    while (low <= high) {        int mid = low + (high - low) / 2;Â
        // If the sum of the natural        // numbers from K to mid is atleast X        if (isGreaterEqual(mid, K, X)) {Â
            // Update res            res = mid;Â
            // Update high            high = mid - 1;        }Â
        // Otherwise, update low        else            low = mid + 1;    }Â
    // Print the value of    // res as the answer    cout << res;}Â
// Driver Codeint main(){Â Â Â Â int K = 5, X = 13;Â Â Â Â minimumNumber(K, X);Â
    return 0;} |
Java
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*;Â
class GFG{Â
// Function to check if the sum of// natural numbers from K to N is >= Xstatic boolean isGreaterEqual(int N, int K, int X){Â Â Â Â return ((N * 1L * (N + 1) / 2) - Â Â Â Â Â Â Â Â Â Â Â ((K - 1) * 1L * K / 2)) >= X;}Â
// Function to find the minimum value// of N such that the sum of natural// numbers from K to N is at least Xstatic void minimumNumber(int K, int X){Â Â Â Â Â Â Â Â Â // If K is greater than XÂ Â Â Â if (K > X)Â Â Â Â {Â Â Â Â Â Â Â Â System.out.println("-1");Â Â Â Â Â Â Â Â return;Â Â Â Â }Â
    int low = K, high = X, res = -1;Â
    // Perform the Binary Search    while (low <= high)    {        int mid = low + (high - low) / 2;Â
        // If the sum of the natural        // numbers from K to mid is atleast X        if (isGreaterEqual(mid, K, X))        {                         // Update res            res = mid;Â
            // Update high            high = mid - 1;        }Â
        // Otherwise, update low        else            low = mid + 1;    }Â
    // Print the value of    // res as the answer    System.out.println(res);}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int K = 5, X = 13;Â Â Â Â Â Â Â Â Â minimumNumber(K, X);}}Â
// This code is contributed by Kingash |
Python3
# Python program for the above approachÂ
# Function to check if the sum of# natural numbers from K to N is >= XÂ
Â
def isGreaterEqual(N, K, X):Â Â Â Â return (((N * (N + 1) // 2)Â Â Â Â Â Â Â Â Â Â Â Â Â - ((K - 1) * K // 2))Â Â Â Â Â Â Â Â Â Â Â Â >= X)Â
# Function to find the minimum value# of N such that the sum of natural# numbers from K to N is at least XÂ
Â
def minimumNumber(K, X):Â Â Â Â # If K is greater than XÂ Â Â Â if (K > X):Â Â Â Â Â Â Â Â print("-1")Â Â Â Â Â Â Â Â returnÂ
    low = K    high = X    res = -1Â
    # Perform the Binary Search    while (low <= high):        mid = low + ((high - low) // 2)Â
        # If the sum of the natural        # numbers from K to mid is atleast X        if (isGreaterEqual(mid, K, X)):Â
            # Update res            res = midÂ
            # Update high            high = mid - 1Â
        # Otherwise, update low        else:            low = mid + 1Â
    # Print the value of    # res as the answer    print(res)Â
Â
# Driver CodeK = 5X = 13minimumNumber(K, X) |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Function to check if the sum of// natural numbers from K to N is >= Xstatic bool isGreaterEqual(int N, int K, int X){Â Â Â Â return ((N * 1L * (N + 1) / 2) - Â Â Â Â Â Â Â Â Â Â Â ((K - 1) * 1L * K / 2)) >= X;}Â
// Function to find the minimum value// of N such that the sum of natural// numbers from K to N is at least Xstatic void minimumNumber(int K, int X){Â
    // If K is greater than X    if (K > X)     {        Console.Write("-1");        return;    }Â
    int low = K, high = X, res = -1;Â
    // Perform the Binary Search    while (low <= high)    {        int mid = low + (high - low) / 2;Â
        // If the sum of the natural        // numbers from K to mid is atleast X        if (isGreaterEqual(mid, K, X))        {                         // Update res            res = mid;Â
            // Update high            high = mid - 1;        }Â
        // Otherwise, update low        else            low = mid + 1;    }Â
    // Print the value of    // res as the answer    Console.WriteLine(res);}Â
// Driver Codepublic static void Main(){Â Â Â Â int K = 5, X = 13;Â
    minimumNumber(K, X);}}Â
// This code is contributed by subham348 |
Javascript
<script>// Javascript program for the above approachÂ
// Function to check if the sum of// natural numbers from K to N is >= Xfunction isGreaterEqual(N, K, X){Â Â Â Â return ((N * parseInt((N + 1) / 2))Â Â Â Â Â Â Â Â Â Â Â Â - ((K - 1) * parseInt(K / 2)))Â Â Â Â Â Â Â Â Â Â Â >= X;}Â
// Function to find the minimum value// of N such that the sum of natural// numbers from K to N is at least Xfunction minimumNumber(K, X){Â Â Â Â // If K is greater than XÂ Â Â Â if (K > X) {Â Â Â Â Â Â Â Â document.write("-1");Â Â Â Â Â Â Â Â return;Â Â Â Â }Â
    let low = K, high = X, res = -1;Â
    // Perform the Binary Search    while (low <= high) {        let mid = low + parseInt((high - low) / 2);Â
        // If the sum of the natural        // numbers from K to mid is atleast X        if (isGreaterEqual(mid, K, X)) {Â
            // Update res            res = mid;Â
            // Update high            high = mid - 1;        }Â
        // Otherwise, update low        else            low = mid + 1;    }Â
    // Print the value of    // res as the answer    document.write(res);}Â
// Driver Codelet K = 5, X = 13;minimumNumber(K, X);Â
// This code is contributed by subham348.</script> |
7
Â
Time Complexity: O(log(X – K))
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



