Minimum number of squares whose sum equals to given number n | Returns count of minimum squares that sum to n ; base cases ; getMinSquares rest of the table using recursive formula Maximum squares required is n ( 1 * 1 + 1 * 1 + . . ) ; Go through all smaller numbers to recursively find minimum ; Driver code
def getMinSquares ( n ) : NEW_LINE INDENT if n <= 3 : NEW_LINE INDENT return n ; NEW_LINE DEDENT res = n NEW_LINE for x in range ( 1 , n + 1 ) : NEW_LINE INDENT temp = x * x ; NEW_LINE if temp > n : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT res = min ( res , 1 + getMinSquares ( n - temp ) ) NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT print ( getMinSquares ( 6 ) ) NEW_LINE