AlgoDaily

Sum of Perfect Squares

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

A perfect square is a number made by squaring a whole number.

Some examples include 1, 4, 9, or 16, and so on -- because they are the squared results of 1, 2, 3, 4, etc. For example:

1^2 = 1
2^2 = 4
3^2 = 9
4^2 = 16
...

However, 15 is not a perfect square, because the square root of 15 is not a whole or natural number.

Perfect Square Factors 1 1 * 1 4 2 * 2 9 3 * 3 16 4 * 4 25 5 * 5 36 6 * 6 49 7 * 7 64 8 * 8 81 9 * 9 100 10 * 10

Given some positive integer n, write a method to return the fewest number of perfect square numbers which sum to n.

The follow examples should clarify further:

var n = 28
howManySquares(n);
// 4
// 16 + 4 + 4 + 4 = 28, so 4 numbers are required

On the other hand:

var n = 16
howManySquares(n);
// 1
// 16 itself is a perfect square
// so only 1 perfect square is required
Constraints
  • n <= 10000
  • n will always be non zero positive integer
  • Expected time complexity : O(n*sqrt(n))
  • Expected space complexity : O(n)
```js
function howManySquares(n) {
  return n;
}

console.log(howManySquares(12));
// 3

console.log(howManySquares(1));
// 1
```

What Are Perfect Squares

The perfect squares are the squares of the whole numbers: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

Step Three

We need to find the least number of perfect squares that sum up to a given number. With problems like this, the brute-force method seems to lean towards iterating through all the possible numbers and performing some operation at each step.

It seems from the get-go that we'll need to find all the perfect squares available to us before we reach the specified number in an iteration.

This means if the number is 30, we'll start at 1, then 2, and conduct a logical step at each number. But what logic do we need? Well, if we're given a number-- say, 100, how would we manually solve this problem and find the perfect squares that sum up to 100?

Like we said, we'd probably just start with 1 and get its perfect square. Then we'll move on to 2, and get the perfect square of 4. But in this case, we'll keep summing as we calculate each square. Mathematically speaking, it would look like:

```
// while (1*1) + (2*2) + (3*3) + (4*4) + ... <= 100
```

Fill in Brute Force

What line below would give us the proper count?

class Main {
    public static int howManySquares(int num) {
        int count = 0;

        for (int i = 1; i <= num; i++)

            // Is current number 'i' a perfect square?
            for (int j = 1; j * j <= i; j++)
                if (j * j == i)
                    _______________________

        return count;
    }

    public static void main(String args[]) {
        this.howManySquares(4);
    }
}

Limiting the Scope

Our brute force solution isn't very optimal, so let's try to make it more efficient. At the very least, notice how we can limit our number of perfect squares to just the ones that are less than our number, since larger ones (in this case, greater than 100) wouldn't make sense. That reduces the time necessary to a degree.

So if we were looking for all the perfect squares that sum up to 12, we wouldn't want to consider 16 or 25-- they're too large for our needs.

To translate this into code, given our previous example, we'd essentially iterate through all numbers smaller than or equal to 100. At each iteration, we'd see if we can find a perfect square that is larger to "fit in" to the "leftover space".

Picture these steps. Start with 28:

Try 16:

Cool, it fits-- let's keep 16. Try 9:

That also fits. What works with 16 and 9?

That won't work-- we can only fit 3 but it's not a perfect square. What else fits with 16?

OK, 4 works, and is a perfect square. Notice that it not only matches both conditions (fits and is a perfect square), but we can fit 3 of them in!

Given that approach, here's the logic translated to code. Read the comments carefully for clarification:

```js
function howManySquares(num) {
	if (num <= 3) {
		return num;
	}

	result = num;

	for (let i = 1; i < num + 1; i++) {
    // get squared number
		temp = i * i;
		if (temp > num) {
			break;
		} else {
      // get whatever is lower:
      // 1 - the current minimum, or
      // 2 - the minimum after considering the next perfect square
			result = Math.min(result, 1 + howManySquares(num - temp));
		}
	}

	return result;
}

console.log(howManySquares(16));
```

Step Six

The above, however, has an exponential time complexity-- that is, O(2^n). Additionally, we don't want to find all the possible perfect squares each time, that wouldn't be very time efficient.

How can we turn this into a shortest path problem? Notice the branching, too-- how might we construct a graph to help us work backwards from a sum to perfect squares? Additionally, there's the opportunity for reuse of calculations.

Well, if we used a data structure for storing the calculations-- let's say a hash, we can memo-ize the calculations. Let's imagine each key in the hash representing a number, and its corresponding value as being the minimum number of squares to arrive at it.

Alternatively, we can use an array, and simply store the sequence of perfect squares for easy lookup.

One Pager Cheat Sheet

One Pager Cheat Sheet

  • Perfect squares are numbers that result from squaring a whole number and can be used to find the fewest number of perfect squares that sum to a given number n, subject to the constraints of n being a nonzero positive integer less than or equal to 10000, and the expected time/space complexity being O(n*sqrt(n))/O(n), respectively.
  • A number is a perfect square when its square root is a whole number, such as the 1st to 10th perfect squares, which are 1, 4, 9, 16, 25, 36, 49, 64, 81, 100.
  • We need to iterate through all possible numbers and perform a logical step at each step to find the least number of perfect squares that sum up to a given number.
  • The for loop will check each number from 1 up to the given number to see if it is a perfect square and count is incremented by 1 for each perfect square found.
  • We can reduce our brute force solution to be more efficient by considering only perfect squares that are less than our target number, and iterating through these to sum them up to the target.
  • We can optimize the time complexity of finding the minimum number of perfect squares needed to add up to a certain sum by turning it into a shortest path problem, constructing a graph and memo-izing the calculations with a hash or an array.
Open interactive view →