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
Check for perfect square in JavaScript
We are required to write a JavaScript function that takes in a number and returns a boolean based on the fact whether or not the number is a perfect square.
A perfect square is a number that can be expressed as the product of an integer with itself. For example, 16 is a perfect square because 4 × 4 = 16.
Examples of Perfect Square Numbers
144 (12²), 196 (14²), 121 (11²), 81 (9²), 484 (22²)
Method 1: Using Math.sqrt()
The most straightforward approach is to find the square root and check if it's an integer:
const isPerfectSquare = (num) => {
if (num < 0) return false;
const sqrt = Math.sqrt(num);
return sqrt === Math.floor(sqrt);
};
console.log(isPerfectSquare(484)); // true
console.log(isPerfectSquare(485)); // false
console.log(isPerfectSquare(121)); // true
console.log(isPerfectSquare(0)); // true
true false true true
Method 2: Using Loop Iteration
This approach iterates through numbers until we find a match or exceed the target:
const isPerfectSquareLoop = (num) => {
if (num < 0) return false;
let i = 1;
while (i * i <= num) {
if (i * i === num) {
return true;
}
i++;
}
return false;
};
console.log(isPerfectSquareLoop(484)); // true
console.log(isPerfectSquareLoop(485)); // false
console.log(isPerfectSquareLoop(144)); // true
true false true
Method 3: Using Binary Search
For better performance with large numbers, binary search can be used:
const isPerfectSquareBinary = (num) => {
if (num < 0) return false;
if (num === 0) return true;
let left = 1;
let right = Math.floor(num / 2) + 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const square = mid * mid;
if (square === num) return true;
if (square < num) left = mid + 1;
else right = mid - 1;
}
return false;
};
console.log(isPerfectSquareBinary(484)); // true
console.log(isPerfectSquareBinary(500)); // false
true false
Comparison
| Method | Time Complexity | Readability | Best For |
|---|---|---|---|
| Math.sqrt() | O(1) | High | Most cases |
| Loop Iteration | O(?n) | Medium | Educational purposes |
| Binary Search | O(log n) | Low | Large numbers |
Conclusion
The Math.sqrt() method is the most efficient and readable approach for checking perfect squares. Use loop-based methods when you need to understand the underlying logic or avoid built-in math functions.
