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 −

 Live Demo

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]

Updated on: 20-Apr-2021

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements