I'm writing a piece of code using JavaScript to check if a number is prime or not. The code correctly tells me the result for number = 1,2,3 but fails on certain others such as 10. I can't figure out what the problem is that is causing it to fail on only certain numbers. If anyone can help identify the problem and suggest a fix I would be grateful.
if (total < 2) {var prime = "this is not a prime number"}
if (total == 2) {prime = "this is a prime number"}
if (total == 3) {prime = "this is a prime number"}
for (var l = 2; l <= Math.sqrt(total); l++) {
if (total % l == 0) {prime = "this is not a prime number"}
else {prime = "this is a prime number"}
}
the code is used in a html file as part of a function
You should exit out of the loop as soon as you know that it's not a prime, otherwise the result will be overwritten in the next itaration. There is actually no point in having the else
clause (as it just sets the same value over and over), just set that value before the loop:
prime = "this is a prime number";
for (var l = 2; l <= Math.sqrt(total); l++) {
if (total % l == 0) {
prime = "this is not a prime number";
break;
}
}
Side note: You don't need to check the values 2
and 3
separately before the loop, those will be catched by the first two iterations in the loop.