- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Returning a range or a number that specifies the square root of a number in JavaScript
Problem
We are required to write a JavaScript function that takes in an integer n and returns either −
- an integer k if n is a square number, such that k * k == n or
- a range (k, k+1), such that k * k < n and n < (k+1) * (k+1).
Example
Following is the code −
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));
Output
Following is the console output −
[9, 10]
Advertisements