function isPrime(n) {
if (n == 1 ) {
return (`${n} is niether a prime number nor composite number`)
}
else if( n < 1){
return (`${n} is not a prime number`)
}
else{
for (let i = 2; i < n; i ) {
if( n % 2 == 0){
return result = `${n} is not a prime number`
break;
}
else{
return result = `${n} is a prime number`
}
}
}
}
console.log(isPrime(15))
I write a function to find the prime number , but it's not working because I'm not able to break the loop
CodePudding user response:
Although answer by Dave addresses the question I would suggest this stack overflow answer as an better alternative.
https://stackoverflow.com/a/38643868/10738743
CodePudding user response:
There are two glitches preventing your function working as intended.
the loop which tests for primeness is repeating
n%2on each iteration, which will evaluate the same, regardless of the value ofiin the loop. Instead, you should be testing to see whethern%iis true.With that fixed, the final
return(which only happens if all non-prime conditions have been rejected with earlierreturns) should be outside of any block as it becomes the default return value.
your code functions fine with the minor changes suggested above incorporated:
function isPrime(n) {
if (n == 1 ) {
return (`${n} is niether a prime number nor composite number`);
}
else if( n < 1){
return (`${n} is not a prime number`)
}
else {
for (let i = 2; i < n; i ) {
if( n % i == 0){
return result = `${n} is not a prime number`
// break; // (return breaks anyway)
} // end if
}// end for i;
} // end else
return result = `${n} is a prime number`; // default after no earlier rejection
}
console.log(isPrime(15));
