Find maximum N such that the sum of square of first N natural numbers is not more than X | 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
function squareSum ( N ) { let sum = parseInt ( ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ) ; return sum ; } function findMaxN ( X ) { let N = Math . sqrt ( X ) ; for ( let i = 1 ; i <= N ; i ++ ) { if ( squareSum ( i ) > X ) return i - 1 ; } return - 1 ; } let X = 25 ; document . write ( findMaxN ( X ) ) ;