Minimum number of squares whose sum equals to given number N | set 2


A number can always be represented as a sum of squares of other numbers. Note that 1 is a square and we can always break a number as (1*1 + 1*1 + 1*1 + …). Given a number N, the task is to represent N as the sum of minimum square numbers.

Examples:

Input : 10
Output : 1 + 9
These are all possible ways
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 4
1 + 1 + 4 + 4
1 + 9
Choose one with minimum numbers

Input : 25
Output : 25

Prerequisites: Minimum number of squares whose sum equals to given number N



Approach : This is a typical application of dynamic programming. When we start from N = 6, we can reach 4 by subtracting one 2 times and by subtracting 2 one times. So the subproblem for 4 is called twice.
Since the same subproblems are called again, this problem has Overlapping Subproblems property. So-min square sum problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array table[][] in a bottom-up manner.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to represent N as the
// sum of minimum square numbers.
#include <bits/stdc++.h>
using namespace std;
  
// Function for finding
// minimum square numbers
vector<int> minSqrNum(int n)
{
    // A[i] of array arr store
    // minimum count of
    // square number to get i
    int arr[n + 1], k;
  
    // sqrNum[i] store last
    // square number to get i
    int sqrNum[n + 1];
    vector<int> v;
  
    // Initialize
    arr[0] = 0;
    sqrNum[0] = 0;
  
    // Find minimun count of
    // square number for
    // all value 1 to n
    for (int i = 1; i <= n; i++) {
        // In worst case it will
        // be arr[i-1]+1 we use all
        // combination of a[i-1] and add 1
        arr[i] = arr[i - 1] + 1;
        sqrNum[i] = 1;
  
        k = 1;
        // Check for all square
        // number less or equal to i
        while (k * k <= i) {
            // if it gives less
            // count then update it
            if (arr[i] > arr[i - k * k] + 1) {
                arr[i] = arr[i - k * k] + 1;
                sqrNum[i] = k * k;
            }
  
            k++;
        }
    }
  
    // Vector v stores optimum
    // square number whose sum give N
    while (n > 0) {
        v.push_back(sqrNum[n]);
        n -= sqrNum[n];
    }
    return v;
}
  
// Driver code
int main()
{
    int n = 10;
  
    vector<int> v;
  
    // Calling funcion
    v = minSqrNum(n);
  
    // Printing vector
    for (auto i = v.begin();
         i != v.end(); i++) {
        cout << *i;
        if (i + 1 != v.end())
            cout << " + ";
    }
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to represent N as the
# sum of minimum square numbers.
  
# Function for finding
# minimum square numbers
def minSqrNum(n):
  
    # arr[i] of array arr store
    # minimum count of
    # square number to get i
    arr = [0] * (n + 1)
      
    # sqrNum[i] store last
    # square number to get i
    sqrNum = [0] * (n + 1)
    v = []
  
    # Find minimun count of
    # square number for
    # all value 1 to n
    for i in range(n + 1):
          
        # In worst case it will
        # be arr[i-1]+1 we use all
        # combination of a[i-1] and add 1
        arr[i] = arr[i - 1] + 1
        sqrNum[i] = 1
  
        k = 1;
          
        # Check for all square
        # number less or equal to i
        while (k * k <= i):
              
            # If it gives less
            # count then update it
            if (arr[i] > arr[i - k * k] + 1):
                arr[i] = arr[i - k * k] + 1
                sqrNum[i] = k * k
  
            k += 1
  
    # v stores optimum
    # square number whose sum give N
    while (n > 0):
        v.append(sqrNum[n])
        n -= sqrNum[n];
          
    return v
  
# Driver code
n = 10
  
# Calling funcion
v = minSqrNum(n)
  
# Printing vector
for i in range(len(v)):
    print(v[i], end = "")
      
    if (i < len(v) - 1):
        print(" + ", end = "")
          
# This article is contributed by Apurvaraj

chevron_right


Output:

1 + 9

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ApurvaRaj