The open blogging platform. Say no to algorithms and paywalls.

JavaScript Algorithm to Check for a Perfect Square Number

Checking if a number is a perfect square

Photo by Vincent LaVigna on UnsplashPhoto by Vincent LaVigna on Unsplash

We are going to write a function called isSquare that will accept an integer n as an argument.

In this function, you will check if a number is a perfect square. A perfect square is an integer that is the square of an integer. In other words, if you were to square root an integer, the result should be another integer. If that's the case, then that integer (the number you square rooted) is a perfect square.

To know whether a number is a perfect square or not, we calculate the square root of the given number. If the result is a whole number then the given number is a perfect square.

If we were to check if 18 is a perfect square, we would square root that number and get 4.24264068712. Since that is not a whole number, we can conclude that 18 is not a perfect square.

But if we did the same for 16 and square root that number, we would get 4. Since 4 is a whole number, we know that 16 is a perfect square.

The goal of the function is to return true if the given value is a perfect square and false if it is not a perfect square.

To begin, we check if the number is positive. Perfect squares can't be negative numbers so if it is a negative number, return false.

if (n < 0) {
    return false;
}

As mentioned above, knowing if a number is a perfect square will depend on the square root of that value. We will use Math.sqrt() to square root the input.

Math.sqrt(n)

To check if the result is a whole number, we will use Number.isInteger() and use our Math.sqrt(n) as an argument.

Number.isInteger(Math.sqrt(n))

With that in mind, we can now check if n is a perfect square. If the square root result is a whole number, the function will return true and if not, return false.

if (Number.isInteger(Math.sqrt(n))) {
    return true;
} else {
    return false;
}

That's it. Here is the rest of the function:

Thank you for reading.




Continue Learning