Find maximum N such that the sum of square of first N natural numbers is not more than X | Python 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
import math NEW_LINE def squareSum ( N ) : NEW_LINE INDENT sum = ( N * ( N + 1 ) * ( 2 * N + 1 ) ) // 6 NEW_LINE return sum NEW_LINE DEDENT def findMaxN ( X ) : NEW_LINE INDENT N = ( int ) ( math . sqrt ( X ) ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( squareSum ( i ) > X ) : NEW_LINE INDENT return i - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT X = 25 NEW_LINE print ( findMaxN ( X ) ) NEW_LINE