Prime number test help


#1

Can anyone help me figure out why my function doesn't work correctly? Just a simple way to test if a number is prime. It keeps returning numbers that are multiples of 5 are prime. Every number ending in 5 I think, 25, 45, 85, etc. But I'm not sure why.

var prime = function(num){
    if(num <= 2){
        return "This is not a Prime number";
    }
    for (var i = 2; i < num; i++){
        if(num % i === 0){
            return "This is not a Prime number.";
        } else {
            return "This is a Prime number!";
        }
    } 
};
    
prime(35);

#2

It's even worse all odd numbers are treated as prime, because you use an if else in your loop as both have a return and at least one is chosen you only loop for i=2 so all even numbers are not prime (ok) but all odd numbers are treated as prime (not ok). Better use just an if there and make the return prime after the for loop.

PS: Also this algorithm only requires to go until square root of num (Math.sqrt()) which makes it a little faster for big numbers.


#3

I tried doing what you were trying to do.:smiley:

Was actually really fun, but included LOTS of if and else if loops. :laughing:

Here, I don't know if this is what you want, but HEY IT WORKS.

var i = 1;
var prime = function(num){
        if(i === 2){
            return "This is a prime number.";
        }
        else if(i === 3){
            return "This is a prime number.";
        }
        else if(i === 5){
            return "This is a prime number.";
        }
        else if(i === 7){
            return "This is a prime number.";
        }
        else if(i === 11){
            return "This is a prime number.";
        }
        else if(i/2===0){
            return "This is not a prime number.";
        }
        else if(i/3===0){
            return "This is not a prime number.";
        }
        else if(i/5===0){
            return "This is not a prime number.";
        }
        else if(i/7===0){
            return "This is not a prime number.";
        }
        else{
            return "This is a prime number.";
        }
};
prime(19865);

Did it with Codecademy Labs. :smiley:

I put in there 19865 as a random number to test it. :smiley:

I don't know if it's like atmost accurate, but it seems to know the problems. :smiley:

I'm actually kind of happy for coding this! :laughing:

But try it. :smiley:


#4

Because your 'else' is inside the for loop, the function will return 'This is a prime number' every time it loops and number%i !== 0, which is probably very often. A better way to do it would be to set a variable, say var isPrime, and have it equal to true at the beginning. Then, if num%i === 0, set it to false. Outside of the loop, return isPrime.

Alternatively you could use a while loop to speed up the code.