const isPrime = (num) => {
for(let i = 1, s = Math.sqrt(num); i <= s; i ){
num % i === 0 ? d.append('number is prime') : d.append(false)
}
}
isPrime(1)
I seem to be missing something in my prime number detector as my turnary operator keeps returning both true and false if a prime number is passed to the function.
CodePudding user response:
There are a few mistakes in the code
- You can't start the loop 1. Every number is divisible by 1, so this will always be true.
- A number is prime if it is divisible by no number less than its square root. You must finish the entire for loop before concluding that it is prime.
- You should exit the for loop with
break
orreturn
after you find the result. If you don't, it will keep appending results until all numbers in the loop are checked.
Here is a slightly modified version to show the points explained above:
const isPrime = (num) => {
for (let i = 2; i <= Math.sqrt(num); i ) {
// if it has a divisor, we know it is not prime
if (num % i === 0) {
d.append('false')
// we want to stop the for loop and exit the function
return
}
}
// if the loop concluded without returning, the number is prime
d.append('number is prime')
}
As a suggestion, I'd also recommend separating the logic from your presentation by having isPrime return true or false, and separately handle your output display.
You can also make this more efficient by checking num === 2 separately and then skipping over all even divisors since 2 is the only prime number divisible by an even divisor.
All together, here is how I'd suggest to improve the code:
const isPrime = (num) => {
if (num < 2) return false; // 1 is not prime
if (num === 2) return true; // 2 is prime
// can skip by 2 since all even numbers after two are not prime
for (let i = 2; i <= Math.sqrt(num); i = 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
const appendPrime = (num) => {
d.append(isPrime(num) ? 'number is prime' : 'false');
}
appendPrime(4)