Friday, November 15, 2024
Google search engine
HomeLanguagesDynamic ProgrammingMinimum number of squares whose sum equals to given number N |...

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 2 by subtracting the square of one i.e. one, 4 times, and by subtracting the square of two i.e. four, 1 time. So the subproblem for 2 is called twice. 
Since the same subproblems are called again, this problem has the 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, recomputation 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++




// 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 minimum 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 function
  v = minSqrNum(n);
 
  // Printing vector
  for (auto i = v.begin();
            i != v.end(); i++)
  {
    cout << *i;
    if (i + 1 != v.end())
      cout << " + ";
  }
  return 0;
}


Java




// Java program to represent
// N as the sum of minimum
// square numbers.
import java.util.*;
class GFG{
 
// Function for finding
// minimum square numbers
static Vector<Integer> minSqrNum(int n)
{
  // A[i] of array arr store
  // minimum count of
  // square number to get i
  int []arr = new int[n + 1];
  int k = 0;
 
  // sqrNum[i] store last
  // square number to get i
  int []sqrNum = new int[n + 1];
  Vector<Integer> v = new Vector<>();
 
  // Initialize
  arr[0] = 0;
  sqrNum[0] = 0;
 
  // Find minimum 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.add(sqrNum[n]);
    n -= sqrNum[n];
  }
  return v;
}
 
// Driver code
public static void main(String[] args)
{
  int n = 10;
 
  Vector<Integer> v;
 
  // Calling function
  v = minSqrNum(n);
 
  // Printing vector
  for (int i = 0; i <v.size(); i++)
  {
    System.out.print(v.elementAt(i));
    if (i+1 != v.size())
      System.out.print(" + ");
  }
}
}
 
// This code is contributed by gauravrajput1


Python3




# 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 minimum 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 function
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


C#




// C# program to represent
// N as the sum of minimum
// square numbers.
using System;
using System.Collections.Generic;
class GFG{
 
// Function for finding
// minimum square numbers
static List<int> minSqrNum(int n)
{
  // A[i] of array arr store
  // minimum count of
  // square number to get i
  int []arr = new int[n + 1];
  int k = 0;
 
  // sqrNum[i] store last
  // square number to get i
  int []sqrNum = new int[n + 1];
  List<int> v = new List<int>();
 
  // Initialize
  arr[0] = 0;
  sqrNum[0] = 0;
 
  // Find minimum 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++;
    }
  }
 
  // List v stores optimum
  // square number whose sum give N
  while (n > 0)
  {
    v.Add(sqrNum[n]);
    n -= sqrNum[n];
  }
  return v;
}
 
// Driver code
public static void Main(String[] args)
{
  int n = 10;
 
  List<int> v;
 
  // Calling function
  v = minSqrNum(n);
 
  // Printing vector
  for (int i = 0; i <v.Count; i++)
  {
    Console.Write(v[i]);
    if (i+1 != v.Count)
      Console.Write(" + ");
  }
}
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
// Javascript program to represent N as the
// sum of minimum square numbers.
 
// Function for finding
// minimum square numbers
function minSqrNum(n)
{
  // A[i] of array arr store
  // minimum count of
  // square number to get i
  var arr = Array(n+1), k;
 
  // sqrNum[i] store last
  // square number to get i
  var sqrNum = Array(n+1);
  var v = [];
 
  // Initialize
  arr[0] = 0;
  sqrNum[0] = 0;
 
  // Find minimum count of
  // square number for
  // all value 1 to n
  for (var 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(sqrNum[n]);
    n -= sqrNum[n];
  }
  return v;
}
 
// Driver code
var n = 10;
var v = [];
// Calling function
v = minSqrNum(n);
// Printing vector
for(var i = 0; i<v.length; i++)
{
    document.write(v[i]);
  if (i + 1 != v.length)
    document.write( " + ");
}
 
 
</script>


Output: 

1 + 9

 

Time Complexity: O(n3/2)

Auxiliary Space: O(n)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments