- Related Questions & Answers
- Program to count number of perfect squares are added up to form a number in C++
- Is a number sum of two perfect squares in JavaScript
- Perfect Squares in C++
- Smallest number that is divisible by first n numbers in JavaScript
- Finding a number of pairs from arrays with smallest sums in JavaScript
- Smallest number after removing n digits in JavaScript
- Find smallest number n such that n XOR n+1 equals to given k in C++
- Minimum number of squares whose sum equals to given number n
- Counting number of 9s encountered while counting up to n in JavaScript
- Finding smallest number that satisfies some conditions in JavaScript
- JavaScript - Find the smallest n digit number or greater
- Python program to filter perfect squares in a given series
- Average of Squares of n Natural Numbers?
- Removing the second number of the pair that add up to a target in JavaScript
- Smallest possible number divisible by all numbers from 1 to n in JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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));

Following is the console output −

3

Advertisements