GeeksforGeeks App
Open App
Browser
Continue

# Find the smallest value of N such that sum of first N natural numbers is ≥ X

Given a positive integer X (1 ≤ X ≤ 106), the task is to find the minimum value N, such that the sum of first N natural numbers is ≥ X.

Examples:

Input: X = 14
Output: 5
Explanation: Sum of first 5 natural numbers is 15 which is greater than X( = 14).

• 1 + 2 = 3( < 14)
• 1 + 2 + 3 = 6( < 14)
• 1 + 2 + 3 + 4 = 10( < 15)
• 1 + 2 + 3 + 4 + 5 = 15( > 14)

Input: X = 91
Output: 13

Naive Approach: The simplest approach to solve this problem is to check every value in the range [1, X] and return the first value from this range for which the sum of the first N natural numbers is found to be ≥ X.

Below is the implementation of the above approach:

## C++

 // C++ Program to implement// the above approach #include using namespace std; // Function to check if sum of first// N natural numbers is >= Xbool isGreaterEqual(int N, int X){    return (N * 1LL * (N + 1) / 2) >= X;} // Finds minimum value of// N such that sum of first// N natural number >= Xint minimumPossible(int X){    for (int i = 1; i <= X; i++) {         // Check if sum of first i        // natural number >= X        if (isGreaterEqual(i, X))            return i;    }} // Driver Codeint main(){    // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    cout << minimumPossible(X);    return 0;}

## Java

 // Java Program to implement// the above approachimport java.io.*;class GFG{     // Function to check if sum of first  // N natural numbers is >= X  static boolean isGreaterEqual(int N, int X)  {    return (N * (N + 1) / 2) >= X;  }   // Finds minimum value of  // N such that sum of first  // N natural number >= X  static int minimumPossible(int X)  {    for (int i = 1; i <= X; i++)    {       // Check if sum of first i      // natural number >= X      if (isGreaterEqual(i, X))        return i;    }    return 0;  }   // Driver Code  public static void main (String[] args)  {         // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    System.out.print(minimumPossible(X));  }} // This code is contributed by Dharanendra L V.

## Python3

 # Python3 Program to implement# the above approach # Function to check if sum of first# N natural numbers is >= Xdef isGreaterEqual(N, X):    return (N * (N + 1) // 2) >= X # Finds minimum value of# N such that sum of first# N natural number >= Xdef minimumPossible(X):     for i in range(1, X + 1):         # Check if sum of first i        # natural number >= X        if (isGreaterEqual(i, X)):            return i # Driver Codeif __name__ == '__main__':         # Input    X = 14     # Finds minimum value of    # N such that sum of first    # N natural number >= X    print (minimumPossible(X))     # This code is contributed by mohit kumar 29.

## C#

 // C# Program to implement// the above approachusing System;public class GFG{   // Function to check if sum of first  // N natural numbers is >= X  static bool isGreaterEqual(int N, int X)  {    return (N * (N + 1) / 2) >= X;  }   // Finds minimum value of  // N such that sum of first  // N natural number >= X  static int minimumPossible(int X)  {    for (int i = 1; i <= X; i++)    {       // Check if sum of first i      // natural number >= X      if (isGreaterEqual(i, X))        return i;    }    return 0;  }   // Driver Code  static public void Main ()  {     // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    Console.Write(minimumPossible(X));  }} // This code is contributed by Dharanendra L V.

## Javascript



Output:

5

Time Complexity : O(N)
Auxiliary Space : O(1)

Efficient Method: Below is the implementation of above approach :

1. The idea is to use binary search to solve this problem.
2. Initialize variables low = 1, high = X and perform binary search on this range.
3. Calculate mid = low + (high – low) / 2 and check if the sum of first mid numbers is greater than or equal to x or not.
4. If sum ≥ X, store it in a variable res and set high = mid-1
5. Otherwise, set low = mid + 1
6. Print res, which is the required answer.

Below is the implementation of the above approach:

## C++

 #include using namespace std; // Function to check if sum of first// N natural numbers is >= Xbool isGreaterEqual(int N, int X){    return (N * 1LL * (N + 1) / 2) >= X;} // Finds minimum value of// N such that sum of first// N natural number >= Xint minimumPossible(int X){     int low = 1, high = X, res = -1;     // Binary Search    while (low <= high) {        int mid = low + (high - low) / 2;         // Checks if sum of first 'mid' natural        // numbers is greater than equal to X        if (isGreaterEqual(mid, X)) {            // Update res            res = mid;            // Update high            high = mid - 1;        }        else            // Update low            low = mid + 1;    }    return res;} // Driver Codeint main(){    // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    cout << minimumPossible(X);    return 0;}

## Java

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

## Python3

 # Function to check if sum of first# N natural numbers is >= Xdef isGreaterEqual(N, X):    return (N * (N + 1) // 2) >= X; # Finds minimum value of# N such that sum of first# N natural number >= Xdef minimumPossible(X):  low = 1  high = X  res = -1;   # Binary Search  while (low <= high):        mid = low + (high - low) // 2;         # Checks if sum of first 'mid' natural        # numbers is greater than equal to X        if (isGreaterEqual(mid, X)):                       # Update res            res = mid;                         # Update high            high = mid - 1;         else:            # Update low            low = mid + 1;   return res # Driver Codeif __name__ == "__main__":       # Input    X = 14;     # Finds minimum value of    # N such that sum of first    # N natural number >= X    print(minimumPossible(X));     # This code is contributed by chitranayal.

## C#

 // C# program for the above approachusing System;class GFG{   // Function to check if sum of first  // N natural numbers is >= X  static bool isGreaterEqual(int N, int X)  {    return (N  * (N + 1) / 2) >= X;  }   // Finds minimum value of  // N such that sum of first  // N natural number >= X  static int minimumPossible(int X)  {    int low = 1, high = X, res = -1;     // Binary Search    while (low <= high)    {      int mid = low + (high - low) / 2;       // Checks if sum of first 'mid' natural      // numbers is greater than equal to X      if (isGreaterEqual(mid, X))      {         // Update res        res = mid;         // Update high        high = mid - 1;      }      else        // Update low        low = mid + 1;    }    return res;  }    // Driver Code  static public void Main()  {    // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    Console.Write( minimumPossible(X));  }} // This code is contributed by susmitakundugoaldanga.

## Javascript



Output:

5

Time Complexity: O(log(X))
Auxiliary Space: O(1)

Another Efficient Approach:

As we know that expression for the sum of the first n natural number is  (n*(n+1))/2.so this expression can be very useful in finding out the value of n from the given X.
From the problem statement, it is quite clear that n * (n + 1) / 2 <= X, so first solve this equation and then use the simplified version of the approach to calculate the value of n for given X.

n * (n + 1) / 2 >=X
=>    n2 + n >= 2X
=>    n2 + n + (1/4 – 1/4) >= 2X
=>    (n + 1/2)2 – 1/4 >= 2X
=>    (n + 1/2)2  >= (2X+1/4)
=>    (n + 1/2) >= sqrt(2X + 1/4)
=>    n >= sqrt(2X + 1/4) – 1/2
The required value of n will be.
=>   n = ceil(sqrt(2X + 1/4) – 1/2)

Below is the implementation of the above approach:

## C++

 // C++ program to implement the approach#include #include  using namespace std; // Finds minimum value of// N such that sum of first// N natural number >= Xint minimumPossible(int X){    return ceil((pow(2 * X + 1 / 4, 0.5) - 0.5));} int main(){    // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    cout << minimumPossible(X) << endl;     return 0;} // This code is contributed by phasing17.

## Java

 // Java Program to implement// the above approach// importing math moduleimport java.util.*; class GFG{     // Finds minimum value of  // N such that sum of first  // N natural number >= X  static int minimumPossible(int X)  {    return (int)Math.ceil((int)Math.pow((2*X+1/4), 0.5)-0.5);  }   // Driver Code  public static void main(String[] args)  {    // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    System.out.print(minimumPossible(X));  }} // This code is contributed by phasing17

## Python3

 # Python3 Program to implement# the above approach# importing math moduleimport math # Finds minimum value of# N such that sum of first# N natural number >= X  def minimumPossible(X):    return math.ceil(((2*X+1/4)**(0.5))-1/2)  # Driver Codeif __name__ == "__main__":    # Input    X = 14    # Finds minimum value of    # N such that sum of first    # N natural number >= X    print(minimumPossible(X))"""This code is contributed by rajatkumargla19 (RAJAT KUMAR)."""

## C#

 // C# Program to implement// the above approach// importing math moduleusing System; class GFG{  // Finds minimum value of  // N such that sum of first  // N natural number >= X  static int minimumPossible(int X)  {    return (int)Math.Ceiling((int)Math.Pow((2*X+1/4), 0.5)-0.5);  }   // Driver Code  public static void Main(string[] args)  {    // Input    int X = 14;     // Finds minimum value of    // N such that sum of first    // N natural number >= X    Console.Write(minimumPossible(X));  }} // This code is contributed by phasing17

## Javascript

 // JS Program to implement// the above approach// importing math module // Finds minimum value of// N such that sum of first// N natural number >= Xfunction minimumPossible(X){    return Math.ceil(((2*X+1/4)**(0.5))-1/2)} // Driver Code // Inputlet X = 14     // Finds minimum value of// N such that sum of first// N natural number >= Xconsole.log(minimumPossible(X)) // This code is contributed by phasing17

Output: 5

Time Complexity: O(log(X)), for calculating the square root of the given X value.
Auxiliary Space: O(1) as no extra space is required here.

My Personal Notes arrow_drop_up