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
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
true
false
true
Method 3: Using Binary Search
For better performance with large numbers, binary search can be used:
const isPerfectSquareBinary = (num) => {
if (num
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.
