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
Returning a range or a number that specifies the square root of a number in JavaScript
We need to write a JavaScript function that takes an integer n and returns either the exact square root (if n is a perfect square) or a range indicating where the square root falls between two consecutive integers.
Problem Requirements
- Return integer k if n is a perfect square, such that k * k == n
- Return a range (k, k+1) if n is not a perfect square, where k * k
Solution Approach
We use Math.sqrt() to calculate the square root, then check if it's a whole number using Math.floor(). If the square root is exact, we return it; otherwise, we return the floor and ceiling values as a range.
Example Implementation
const num = 83;
const squareRootRange = (num = 1) => {
const exact = Math.sqrt(num);
if(exact === Math.floor(exact)){
return exact;
} else {
return [Math.floor(exact), Math.ceil(exact)];
}
};
console.log(squareRootRange(num));
[9, 10]
Testing with Perfect Squares
Let's test the function with perfect squares to see when it returns a single integer:
console.log(squareRootRange(16)); // Perfect square console.log(squareRootRange(25)); // Perfect square console.log(squareRootRange(30)); // Not a perfect square console.log(squareRootRange(49)); // Perfect square
4 5 [5, 6] 7
How It Works
The function calculates Math.sqrt(num) and stores it in exact. If this value equals Math.floor(exact), it means the square root is a whole number (perfect square). Otherwise, we return an array containing the floor and ceiling of the square root, representing the range where the actual square root lies.
Conclusion
This solution efficiently determines whether a number is a perfect square and returns either the exact square root or the bounding range. The approach leverages JavaScript's built-in Math functions for accurate calculations.
