# Smallest number of perfect squares that sums up to n in JavaScript

We are required to write a JavaScript function that takes in a positive number, say num, as the only argument.

The function should find a combination of such perfect square numbers which when added gives the number provided as input. We have to make that we make use of as less as possible number of perfect squares.

For example −

If the input number is −

const num = 123;

Then the output should be −

const output = 3;

because 123 = 121 + 1 + 1

This is a classic Dynamic Programming problem where we can reach the result for a particular number based on the results of its preceding numbers.

Before jumping straight into the code lets first try to understand a general pattern and how actually DP will help us in devising the solution.

The result for six five numbers will be −

1 --> 1 (1)
2 --> 2 (1 + 1)
3 --> 3 (1 + 1 + 1)
4 --> 1 (4)
5 --> 2 (4 + 1)
6 --> 3 (4 + 1 + 1)

This clearly shows we have to try and try combination in preceding results to obtain succeeding results.

## Example

Following is the code −

const num = 123;
const sumSquares = (num) => {
let arr = new Array(num + 1).fill(0);
arr[1] = 1;
for(let i = 1; i * i <= num; i++) {
for(let j = i * i; j < arr.length; j++) {
if(arr[j] == 0) {
arr[j] = arr[j - (i * i)] + 1;
} else {
arr[j] = Math.min(arr[j - (i * i)] + 1, arr[j]);
}
}
};
return arr[num];
};
console.log(sumSquares(num));

## Output

Following is the console output −

3

Advertisements