How to use the Math.sqrt() Function In Javascript
The simplest approach to checking whether a number is a perfect square is to use the Math.sqrt() function. If the square root of a number results in an integer, then the number is a perfect square.
Example: It returns true if the input number is a perfect square (i.e., an integer that is the square of an integer), otherwise false. It also includes examples of usage demonstrating its functionality.
function isPerfectSquare(num) {
if (num <= 0 || typeof num !== "number") {
return false;
}
const sqrt = Math.sqrt(num);
return Number.isInteger(sqrt);
}
const number1 = 16;
const number2 = 9;
const number3 = 15;
console.log(`${number1} is perfect square:
${isPerfectSquare(number1)}`);
console.log(`${number2} is perfect square:
${isPerfectSquare(number2)}`);
console.log(`${number3} is perfect square:
${isPerfectSquare(number3)}`);
Output
16 is perfect square: true 9 is perfect square: true 15 is perfect square: false
JavaScript Program to Check Whether a Number is Perfect Square
The number that results from squaring another integer is called a perfect square. A perfect square is a number that can be expressed as the product of an integer with itself. There are several ways available in JavaScript to check whether a number is a perfect square or not which are as follows:
Table of Content
- Using the Math.sqrt() Function
- Using for loop
- Using binary search
- Using prime factorization
Contact Us