JavaScript Program to Check Whether a Number is Perfect Square
Last Updated :
14 Jun, 2024
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:
Using the Math.sqrt() Function
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.
JavaScript
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)}`);
Output16 is perfect square: true
9 is perfect square: true
15 is perfect square: false
Using for loop
One can iterate from 1 to the square root of the number using for loop and check if any integer square results in the given number.
Example: It starts at 1 and iterates through possible square roots until the iterator's square reaches the specified number. It returns true if the square of any iterator is equal to the given integer, displaying that the number is a perfect square; if not, it returns false.
JavaScript
function isPerfectSquare(num) {
// Check for negative and non-numeric input
if (num <= 0 || typeof num !== "number") {
return false;
}
// Loop through potential square roots
for (let i = 1; i * i <= num; i++) {
if (i * i === num) {
return true;
}
}
return false;
}
// Example usage
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)}`);
Output16 is perfect square: true
9 is perfect square: true
15 is perfect square: false
Using binary search
A more optimized approach is to use binary search to find the square root of the number. We can narrow down the search range by halving it in each iteration.
Example: It utilizes a binary search approach to find if the square of any number between 1 and num is equal to the given number. If found, it returns true, indicating that the number is a perfect square; otherwise, it returns false
JavaScript
function isPerfectSquare3(num) {
let left = 1;
let right = num;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
let square = mid * mid;
if (square === num) {
return true;
} else if (square < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
const number1 = 16;
const number2 = 9;
const number3 = 15;
console.log(`${number1} is perfect square:
${isPerfectSquare3(number1)}`);
console.log(`${number2} is perfect square:
${isPerfectSquare3(number2)}`);
console.log(`${number3} is perfect square:
${isPerfectSquare3(number3)}`);
Output16 is perfect square: true
9 is perfect square: true
15 is perfect square: false
Using prime factorization
Another approach to determine if a number is a perfect square involves prime factorization. If the prime factors of a number occur in pairs, then the number is a perfect square. This is because when you multiply these pairs together, you get the original number.
Example: This method involves finding the prime factors of the given number and checking if each factor occurs an even number of times.
JavaScript
function isPerfectSquare4(num) {
// Check for negative and non-numeric input
if (num <= 0 || typeof num !== "number") {
return false;
}
// Find the prime factors
let factorCount = new Map();
let divisor = 2;
while (num > 1) {
if (num % divisor === 0) {
num /= divisor;
factorCount.set(divisor, (factorCount.get(divisor) || 0) + 1);
} else {
divisor++;
}
}
// Check if each factor occurs an even number of times
for (let count of factorCount.values()) {
if (count % 2 !== 0) {
return false;
}
}
return true;
}
// Example usage
const number1 = 16;
const number2 = 9;
const number3 = 15;
console.log(`${number1} is perfect square: ${isPerfectSquare4(number1)}`);
console.log(`${number2} is perfect square: ${isPerfectSquare4(number2)}`);
console.log(`${number3} is perfect square: ${isPerfectSquare4(number3)}`);
Output16 is perfect square: true
9 is perfect square: true
15 is perfect square: false
Similar Reads
JavaScript Program to Check Whether a Number is an Automorphic Number
Numbers, whose square ends with the same digits as the number itself are referred to as automorphic numbers, sometimes known as circular or circular-permuted numbers. Examples:Input: number = 5Output: YesExplanation: 5 is a automorphic number, because the square of 5 is 25 which ends with 5 the digi
3 min read
JavaScript Program to find All Divisors of a Natural Number
In this article, we are going to implement a program through which we can find the divisors of any natural number. Divisors refer to the numbers by which we can divide another number, resulting in zero remainder. These divisors are also commonly referred to as factors. Example: Input: 14Output: 1,2,
2 min read
JavaScript Program to Check whether the Input Number is a Neon Number
A neon number is a number where the sum of digits of its square equals the number itself. For example, 9 is a neon number because 9^2 = 81, and the sum of the digits 81 is 9. There are several ways to check if a given number is a neon number in JavaScript or not which are as follows: Table of Conten
2 min read
Java Program to Check if a Given Number is Perfect Number
A number is said to be a perfect number if the sum of its proper divisors ( i.e. all positive divisors excluding the number itself )is equal to that number itself. Aliquot sum is the sum of divisors of a number, excluding the number itself. Hence, a number is a perfect number only if it is equal to
5 min read
JavaScript Program to Check Prime Number By Creating a Function
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this article, we will explore how to check if a given number is a prime number in JavaScript by creating a function. Table of Content Check Prime Number using for LoopCheck Prime Number using
2 min read
Different Methods to Check whether is the number is Square root or not in Java
In this article, we will learn different methods to check whether the number is a square root or not in Java. Examples: Input: x = 4Output: 4 is a perfect square: True Input: x = 11Output: 3Explanation: 11 is a perfect square: False Methods to Check Square Root in JavaBelow are the methods by which
5 min read
PHP Check if Given Number is Perfect Square
Given a number, the task is to check the given number is a perfect square in PHP. A perfect square is an integer that is the square of another integer. For example, 16 is a perfect square because it is the square of 4. Examples: Input: num = 16Output: Perfect SquareInput: 18Output: Not a Perfect Squ
2 min read
Java Program to Check If a Number is Neon Number or Not
A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range. Illustration: Case 1: Input : 9 Output : Given number 9 is Neon number Explanation : square of 9=9*9=81; sum of digit of square : 8+1=9(which
3 min read
Program to find the perimeter of a square given its area
Write a program to find the perimeter of a square given its area. Examples: Input: Area = 36 square unitsOutput: Perimeter = 24 unitsExplanation: Since the area of the square is 36 square units, so the side of square will be 6 units. Therefore, the perimeter of the square will be 4 * 6 = 24 units. I
3 min read
Find the smallest four digit number which is a perfect square
The arithmetic value which is used for representing the quantity and used in making calculations are defined as Numbers. A symbol like â4,5,6â which represents a number is known as numerals. Without numbers, we can't do counting of things, date, time, money, etc. these numbers are also used for meas
7 min read