Find maximum N such that the sum of square of first N natural numbers is not more than X in C++

C++Server Side ProgrammingProgramming

Concept

With respect of a given integer X, our task is to determine the maximum value N so that the sum of first N natural numbers should not exceed X.

Input

X = 7

Output

2

2 is the maximum possible value of N because for N = 3, the sum of the series will exceed X i.e. 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14

Input

X = 27

Output

3

3 is the maximum possible value of N because for N = 4, the sum of the series will exceed X i.e. 1^2 + 2^2 + 3^2 + 4^2 = 1 + 4 + 9 + 16 = 30

Method

Simple Solution − Here, a simple solution is to execute a loop from 1 till the maximum N so that S(N) ≤ X, in this case S(N) is termed as the sum of square of first N natural numbers. As a result of this, sum of square of first N natural numbers is given by the formula S(N) = N * (N + 1) * (2 * N + 1) / 6.

It should be noted that the time complexity of this approach is O(N).

Efficient Approach − We can implement another efficient solution which is based on binary search approach.

We follow the below algorithm which is explained step by step −

  • Begin binary search in bigger array and get mid as (low + high) / 2

  • It has been seen that if value from both array is same then element must be in right part so mark low as mid

  • Else mark high as mid as element must be in left part of bigger array if mid elements is not same.

It should be noted that the time complexity of this approach is O(log N).

Example

 Live Demo

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
// Shows function to return the sum of the squares
// of first N1 natural numbers
ll squareSum(ll N1){
   ll sum1 = (ll)(N1 * (N1 + 1) * (2 * N1 + 1)) / 6;
   return sum1;
}
// Shows function to return the maximum N such that
// the sum of the squares of first N
// natural numbers is not more than X
ll findMaxN(ll X){
   ll low1 = 1, high1 = 100000;
   int N1 = 0;
   while (low1 <= high1) {
      ll mid1 = (high1 + low1) / 2;
      if (squareSum(mid1) <= X) {
         N1 = mid1;
         low1 = mid1 + 1;
      }
      else
         high1 = mid1 - 1;
   }
   return N1;
}
// Driver code
int main(){
   ll X = 27;
   cout << findMaxN(X);
   return 0;
}

Output

3
raja
Published on 25-Jul-2020 12:13:49
Advertisements