Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Is a number 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 by itself.
For instance, 9, 16, 81, 289 are all perfect squares because:
- 9 = 3 × 3
- 16 = 4 × 4
- 81 = 9 × 9
- 289 = 17 × 17
We need to write a JavaScript function that takes a natural number as input and determines whether it can be expressed as the sum of two perfect squares:
(m * m) + (n * n) = num
If such numbers m and n exist, the function should return true, otherwise false.
Example
For the input number 389:
const num = 389;
The output should be true because 389 = (17 × 17) + (10 × 10) = 289 + 100
Solution Using Two-Pointer Approach
The algorithm uses two pointers: one starting from 0 and another from the square root of the target number. We check if their squares sum to the target:
const num = 389;
const canSumSquares = (num = 2) => {
let left = 0, right = Math.floor(Math.sqrt(num));
while (left <= right) {
const sum = left * left + right * right;
if (sum === num) {
return true;
} else if (sum < num) {
left++;
} else {
right--;
}
}
return false;
};
console.log(`Can ${num} be expressed as sum of two squares? ${canSumSquares(num)}`);
Can 389 be expressed as sum of two squares? true
Testing with Multiple Examples
Let's test the function with different numbers to see how it works:
const canSumSquares = (num = 2) => {
let left = 0, right = Math.floor(Math.sqrt(num));
while (left <= right) {
const sum = left * left + right * right;
if (sum === num) {
return true;
} else if (sum < num) {
left++;
} else {
right--;
}
}
return false;
};
// Test cases
const testNumbers = [389, 25, 50, 13, 7];
testNumbers.forEach(num => {
const result = canSumSquares(num);
console.log(`${num}: ${result}`);
});
389: true 25: true 50: true 13: true 7: false
How It Works
The algorithm works by:
- Setting
left = 0andright = ?num - Calculating
left² + right² - If the sum equals the target, return
true - If the sum is less than target, increment
left - If the sum is greater than target, decrement
right - Continue until
left > right
This approach has O(?n) time complexity, making it efficient for large numbers.
Conclusion
The two-pointer technique provides an efficient way to check if a number can be expressed as the sum of two perfect squares. This algorithm systematically explores all possible combinations in O(?n) time.
