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
function getMinSquares ( n ) { if ( n <= 3 ) return n ; let res = n ; for ( let x = 1 ; x <= n ; x ++ ) { let temp = x * x ; if ( temp > n ) break ; else res = Math . min ( res , 1 + getMinSquares ( n - temp ) ) ; } return res ; } document . write ( getMinSquares ( 6 ) ) ;