Below is my code to check whether a number is prime or not:
function isPrime(num) {
if (num === 2) {
return true;
} else if (num > 1) {
for (var i = 2; i < num; i++) {
if (num % i !== 0) {
return true;
} else if (num === i * i) {
return false
} else {
return false;
}
}
} else {
return false;
}
}
console.log(isPrime(121));
When I run the above code, it doesn’t work for the square of odd prime numbers. For example, 9 returns true instead of false.
Can anyone tell me how to do a prime number test in JavaScript?