Given an integer X, the task is to find the maximum value N such that the sum of first N natural numbers is not more than X.
Input: X = 5
2 is the maximum possible value of N because for N = 3, the sum of the series will exceed X
i.e. 12 + 22 + 32 = 1 + 4 + 9 = 14
Input: X = 25
Simple Solution: A simple solution is to run a loop from 1 till the maximum N such that S(N) ≤ X, where S(N) is the sum of square of first N natural numbers. Sum of square of first N natural numbers is given by the formula S(N) = N * (N + 1) * (2 * N + 1) / 6. The time complexity of this approach is O(N).
Efficient Approach: An efficient solution is to use Binary Search to find the value of N. The time complexity of this approach is O(log N).
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find the permutation of first N natural numbers such that sum of i % Pi is maximum possible
- Sum of square-sums of first n natural numbers
- Maximum LCM among all pairs (i, j) of first N natural numbers
- Find all divisors of first N natural numbers
- Find the average of first N natural numbers
- Find m-th summation of first n natural numbers.
- Find if given number is sum of first n natural numbers
- Find sum of N-th group of Natural Numbers
- Program to find sum of first n natural numbers
- Find all Factors of Large Perfect Square Natural Number in O(sqrt(sqrt(N))
- Find the K-th Permutation Sequence of first N natural numbers
- Find the good permutation of first N natural numbers
- Find the count of natural Hexadecimal numbers of size N
- Find permutation of first N natural numbers that satisfies the given condition
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.