Returning a range or a number that specifies the square root of a number in JavaScript

JavascriptWeb DevelopmentFront End Technology

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]
raja
Published on 20-Apr-2021 08:11:35
Advertisements