Find maximum N such that the sum of square of first N natural numbers is not more than X | C ++ implementation of the approach ; Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int squareSum ( int N ) { int sum = ( int ) ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ; return sum ; } int findMaxN ( int X ) { int low = 1 , high = 100000 ; int N = 0 ; while ( low <= high ) { int mid = ( high + low ) / 2 ; if ( squareSum ( mid ) <= X ) { N = mid ; low = mid + 1 ; } else high = mid - 1 ; } return N ; } int main ( ) { int X = 25 ; cout << findMaxN ( X ) ; return 0 ; }