hackrnaut
hackrnaut

Reputation: 583

Prime factor in javascript, why is this case not working?

I'm writing a primality checker in in j/s and I was wondering why I'm getting true as a return for when I test 55... It seems to work fine for all the other cases I checked just not 55, can someone tell me where I went wrong?

var isPrime = function(num){

    if (num === 2){
        return true;
    }
    else if(num%2 === 0){
        return false;
    }
    else{
        var i = 2;
        while(i<num){

            if((num/i) % i === 0 ){
                return false;
            }
                i++
        }
        return true;
    }

};

Thanks in advance and apologies for the noobness!

Upvotes: 1

Views: 95

Answers (4)

mkraemerx
mkraemerx

Reputation: 1843

Even if your bug may be solved, I'd recommend to think about some other aspects to optimize your code:

  1. Clarify your corner cases: In the beginning, check for n<2 -> return false. At least to math theory primes are defined as natural number larger then 1, so 1 is by definition not a prime like all the negative numbers. Your code won't handle negative numbers correctly.
  2. You don't have to check all divisors up to n-1. You can obviously stop checking at n/2, but there are even proofs for tighter bounds which means you can stop checking already at √n if I'm right. To further optimize, you don't have to check even divisors >2.

    else {
      var i = 3;
      while ( i < num/2 ) {
        if( num % i == 0 ) {
            return false;
        }
        i+=2;
      }
      return true;
    }
    

    See https://en.wikipedia.org/wiki/Primality_test for details about testing of primes.

P.S: I just wrote the code here in the text box, but it looks like it might work.

Upvotes: 0

Oshadha
Oshadha

Reputation: 548

Try this.

var isPrime = function isPrime(value) {
    var i = 2;
    for(i; i < value; i++) {
        if(value % i === 0) {
            return false;
        }
    }
    return value > 1;
};

Upvotes: 0

small_data88
small_data88

Reputation: 380

Just as @Andrey pointed out, your if statement inside the while loop is not correct. For 55 at i=5 you should get false for 55 being prime, but 55/5 % 5 == 1 Also you could use just == instead of === for logical equals, since === checks if both values and type are equal, which is not necessary here.

Upvotes: 1

Andrey
Andrey

Reputation: 4050

       if((num/i) % i === 0 ){
            return false;
       }

What is this case? Shouldn't it be

       if(num % i === 0 ){
            return false;
       }

Upvotes: 2

Related Questions