Minimum number of squares whose sum equals to given number N | set 2 Last Updated : 05 Nov, 2021 Summarize Comments Improve Suggest changes Share Like Article Like Report 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 NApproach: 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) Comment More infoAdvertise with us Next Article Minimum number of squares whose sum equals to given number N | set 2 K kartik Follow Improve Article Tags : Dynamic Programming Mathematical DSA Practice Tags : Dynamic ProgrammingMathematical Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ 3 min read Like