I am trying to make a javaScript function to check the prime number. It's perfectly working for lot of all the numbers I've tested but only comes wrong output when the value is 9. Could you please anyone check below code and advise?
const primeDetector = function (inputNumber) {
if (inputNumber < 1) {
console.log("Your input is not a prime");
}
if (inputNumber === 1) {
console.log("Your input is Neither prime nor composite");
}
if (inputNumber === 2) {
console.log(`${inputNumber} is a prime number`);
} else if (inputNumber > 2) {
for (var i = 2; i < inputNumber; i ) {
if (inputNumber % i == 0) {
console.log(`${inputNumber} is NOT a prime number`);
break;
} else {
console.log(`${inputNumber} is a PRIME number`);
break;
}
}
}
};
primeDetector();
CodePudding user response:
As far as I can tell your function only checks if a number is even or odd, because you break the loop instantly. You are just checking i=2
.
CodePudding user response:
The problem is that you are forgetting that you are doing your check in a loop. You treat it as if it is not in a loop:
for (var i = 2; i < inputNumber; i ) {
if (inputNumber % i == 0) {
console.log(`${inputNumber} is NOT a prime number`);
break;
} else {
console.log(`${inputNumber} is maybe a PRIME number, if I don't say it is not a prime number at the end then it is PRIME, right now I'm not sure yet`);
// break; // <-- this break is the bug
}
}
Remember, this is a loop. If the number is not divisible by i
then it does NOT mean it is a prime but it just means you have not tested with all the values of i
yet. You still need to complete the loop to test all the values of i.
If you want to only print one message when it is a prime you need to remember if you have passed the test or not. In programming, remembering means using memory and using memory means using a variable:
var is_prime = true;
for (var i = 2; i < inputNumber; i ) {
if (inputNumber % i == 0) {
console.log(`${inputNumber} is NOT a prime number`);
is_prime = false;
break;
}
}
// We only know if the number is a prime HERE
// not inside the loop above
if (is_prime) {
console.log(`${inputNumber} is PRIME`);
}