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.
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:
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.
- Minimum number of squares whose sum equals to given number n
- Minimum number of squares whose sum equals to a given number N | Set-3
- Minimum number of cubes whose sum equals to given number N
- Paper Cut into Minimum Number of Squares
- Paper Cut into Minimum Number of Squares | Set 2
- Number of ways of writing N as a sum of 4 squares
- Number of perfect squares between two given numbers
- Check whether a number can be represented by sum of two squares
- Count number of squares in a rectangle
- Square pyramidal number (Sum of Squares)
- Find the number of pairs such that their gcd is equals to 1
- Find smallest number n such that n XOR n+1 equals to given k.
- Number of squares of maximum area in a rectangle
- Check whether a number can be represented by the product of two squares
- Check whether a number can be represented as difference of two squares
- Sum of the count of number of adjacent squares in an M X N grid
- Count number less than N which are product of perfect squares
- Number of Co-prime pairs from 1 to N with product equals to N
- Smallest number greater or equals to N such that it has no odd positioned bit set
- Minimum number of distinct powers of 2 required to express a given binary number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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