Given a positive integer n, find the minimum number of squares that sums to n.

For example,

Input: 100
Output: 1
100 is a perfect square. It can be represented as 102.
 
Input: 10
Output: 2
10 can be represented as 32 + 12.
 
Input: 63
Output: 4
63 can be represented as 72 + 32 + 22 + 12.

Practice this problem

The idea is to use recursion. For each positive integer i <= √n, recur for n-i2 and find the minimum number of squares that sum to n. This is demonstrated below in C++ and Java:

C++


Download  Run Code

Output:

The minimum number of squares is 4

Java


Download  Run Code

Output:

The minimum number of squares is 4

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack). The problem can be recursively broken down into smaller subproblems, and each subproblem gets repeated several times. The repeated subproblems can be easily seen by drawing a recursion tree.

 
Since the problem satisfies optimal substructure and overlapping subproblems properties of dynamic programming, the subproblem solution can be derived in a bottom-up manner. Following is the dynamic programming solution in C, Java, and Python, where an auxiliary array is used to store solutions to the smaller subproblems:

C


Download  Run Code

Output:

The minimum number of squares is 4

Java


Download  Run Code

Output:

The minimum number of squares is 4

Python


Download  Run Code

Output:

The minimum number of squares is 4

The time complexity of the above solution is O(n.√n), and the extra space used by the program is O(n).