
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a Number is Sum of Two Perfect Squares in JavaScript
Perfect Square Numbers:
A natural number in mathematics is called a perfect square if it can be obtained by multiplying any other natural number into that very number.
For instance, 9, 16, 81, 289 are all perfect squares.
We are required to write a JavaScript function that takes in a natural number, say num, as the only argument. The function should determine whether there exists two such number m and n such that −
(m * m) + (n * n) = num
If there exists such numbers, our function should return true, false otherwise.
For example −
If the input number is −
const num = 389;
Then the output should be −
const output = true;
because 389 = (17 * 17) + (10 * 10)
Example
The code for this will be −
const num = 389; const canSumSquares = (num = 2) => { let left = 0, right = Math.floor(Math.sqrt(num)); while(left <= right){ if (left * left + right * right === num) { return true; } else if (left * left + right * right < num) { left++; } else { right--; }; }; return false; }; console.log(canSumSquares(num));
Output
And the output in the console will be −
true
Advertisements