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 ; Iterate till maxvalue of N ; If the condition fails then return the i - 1 i . e sum of squares till i - 1 ; 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 N = sqrt ( X ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( squareSum ( i ) > X ) return i - 1 ; } return -1L ; } int main ( ) { int X = 25 ; cout << findMaxN ( X ) ; return 0 ; }