- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- 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
- Finding a number of pairs from arrays with smallest sums in JavaScript
- Smallest number that is divisible by first n numbers in JavaScript
- Smallest number after removing n digits in JavaScript
- Perfect Squares in C++
- Counting number of 9s encountered while counting up to n 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
- JavaScript - Find the smallest n digit number or greater
- Finding smallest number that satisfies some conditions in JavaScript
- Smallest possible number divisible by all numbers from 1 to n in JavaScript
- Write the smallest number that must be subtracted from 9400 to obtain a perfect square.Find this perfect square and its square root.
- Find the smallest number which must be added to 2300 so that it becomes a perfect square.
- Program to find any two numbers in a list that sums up to k in Python
