Minimum number of squares whose sum equals to given number n | A dynamic programming based Python program to find minimum number of squares whose sum is equal to a given number ; Returns count of minimum squares that sum to n ; getMinSquares table for base case entries ; getMinSquares rest of the table using recursive formula ; max value is i as i can always be represented as 1 * 1 + 1 * 1 + ... ; Go through all smaller numbers to recursively find minimum ; Store result ; Driver code
from math import ceil , sqrt NEW_LINE def getMinSquares ( n ) : NEW_LINE INDENT dp = [ 0 , 1 , 2 , 3 ] NEW_LINE for i in range ( 4 , n + 1 ) : NEW_LINE INDENT dp . append ( i ) NEW_LINE for x in range ( 1 , int ( ceil ( sqrt ( i ) ) ) + 1 ) : NEW_LINE INDENT temp = x * x ; NEW_LINE if temp > i : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , 1 + dp [ i - temp ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT print ( getMinSquares ( 6 ) ) NEW_LINE