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 ; Driver Code
function squareSum ( N ) { var sum = parseInt ( ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ) ; return sum ; } function findMaxN ( X ) { var low = 1 , high = 100000 ; var N = 0 ; while ( low <= high ) { var mid = ( high + low ) / 2 ; if ( squareSum ( mid ) <= X ) { N = parseInt ( mid ) ; low = mid + 1 ; } else high = mid - 1 ; } return N ; } var X = 25 ; document . write ( findMaxN ( X ) ) ;