andthatch - 5 months ago 40
Javascript Question

# Issue with prime number test javascript

I'm a beginner and trying to complete a prime number test but I'm running into an issue. Here is what I have:

``````var n = Number(prompt("Input the number you want to check for prime:"));
var i;

if (n < 2) {
alert(n + " is not a prime number.");
}
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
alert(n + " is not a prime number.");
break;
}

else {
alert(n + " is a prime number.");
break;
}
}
``````

It's running correctly except an alert won't pop up if I input 3 or 2 and any number with a 3 in it is coming back as a prime number even if it isn't. Other than that all of my tests have worked.

Ahhh, your problem is the way you've structured the loop. You're breaking out regardless of if the check's completed.

``````var n = Number(prompt("Input the number you want to check for prime:"));
var i;
var isPrime = true;

if (n < 2) {
isPrime = false;
} else if (n < 4 && n >= 2) {
} else if (n % 2 === 0) {
isPrime = false; // no divisor of 2 can be prime
} else {
var sqrtN = Math.sqrt(n);
for (var i = 3; i <= sqrtN; i = i + 2) {
if (n % i === 0) {
// Only break out of the loop if a match is found
isPrime = false;
break;
}
}
}
if (isPrime) {
alert(n + " is a prime number.");
} else {
alert(n + " is not a prime number.");
}
``````

Or, a perhaps more organized solution:

``````function isPrime (n) {
n = parseInt(n);
var i;
if (Number.isNaN(n)) {
return false;
} else if (n < 2) {
// 1 is not prime
return false;
} if (n < 4) {
// 2 and 3 are prime, so why not skip checking them?
return true;
} else if (n % 2 === 0) {
// No number divisible by 2 is prime.
return false;
} else {
// This won't change, so calculate it once as suggested by Weather Vane.
var sqrtN = Math.sqrt(n);
// 4, 6, 8... All divisible by 2, and would be caught by initial check.
for (i = 3; i < sqrtN; i = i + 2) {
// Not a prime if it's evenly divisible.
if (n % i === 0) {
return false;
}
}
// Otherwise prime.
return true;
}
}
``````
Source (Stackoverflow)