How to use prime factorization In Javascript
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.
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)}`);
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