My isPrime function for some reason does not work for multiples of 3.
console.log(isPrime(9))
returns me true
, when the number is clearly not prime. I have been staring at the logic for a while and multiple google searches yield nothing, so I am assuming it is some really dumb oversight. I could probably copy and paste to make it work but I am attempting to build proper understanding.
function isPrime(num){
for (let i = 2; i < Math.sqrt(num); i ){
if (num % i == 0){
return false;
}
return true;
}
}
console.log(isPrime(9));
CodePudding user response:
i <
needs to be replaced withi <=
- I added a variable to store the
Math.sqrt
call since that's an expensive operation to do every iteration. - Your first iteration returns
true
orfalse
immediately. You should remove thereturn true
from thefor
loop completely to let it iterate.
function isPrime(num){
let max = Math.sqrt(num);
for (let i = 2; i <= max; i ){
if (num % i == 0){
return false;
}
}
return true;
}
console.log(isPrime(1));
console.log(isPrime(2));
console.log(isPrime(3));
console.log(isPrime(4));
console.log(isPrime(5));
console.log(isPrime(7));
console.log(isPrime(8));
console.log(isPrime(9));
console.log(isPrime(10));
CodePudding user response:
Instead of Math.sqrt
you should write num
.