Check for perfect square without using Math libraries - 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.

Examples of perfect square numbers −

4, 16, 81, 441, 256, 729, 9801

Let’s write the code for this function −

const num = 81; const isPerfectSquare = num => {    let ind = 1;       while(ind * ind <= num){          if(ind * ind !== num){             ind++;             continue;          };       return true;    };    return false; }; console.log(isPerfectSquare(81)); console.log(isPerfectSquare(9801)); console.log(isPerfectSquare(99)); console.log(isPerfectSquare(441)); console.log(isPerfectSquare(7648));

Output

Following is the output in the console −

true true false true false
Updated on: 2020-09-14T14:30:36+05:30

382 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements