JavaScript(JS) JS check prime number
To check whether a given number is a prime number using JavaScript, you can use the following code:
reot ref:theitroad.comfunction isPrime(n) {
if (n <= 1) {
return false;
}
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
// Example usage:
console.log(isPrime(7)); // Output: true
console.log(isPrime(12)); // Output: false
In this code, we define a function called isPrime that takes in one parameter n representing the number to check.
We first check if the number is less than or equal to 1, as 1 is not considered a prime number. If so, we immediately return false.
We then loop through all numbers from 2 to the square root of n, checking if n is divisible by any of these numbers. If so, we immediately return false as n is not a prime number.
If we finish the loop and haven't returned false, then n is a prime number and we return true.
