vendredi 18 décembre 2020

(Javascript) Prime numbers in a given interval: for loop doesn't iterate

In the code below is a prime test function (returns true if prime and false if not). I am using it to print out prime numbers between 5 and 20.

The expected output is obviously 5,7,11,13,17,19

The for loop doesn't seem to iterate and just stays at 5. The output is as if the script is stuck inside an infinite while loop.

I don't know what I'm doing wrong, maybe the if statement isn't written correctly? Still a bit new to javascript.

function is_prime(number){

    if (number==2 || number==3){
        return true;
    }
    
    if (number==0 || number==1 || number%2==0){
        return false;
    }

    if ((number+1)%6!=0 && (number-1)%6!=0){
        return false;
    }
    
    for(i=3; i-1<=parseInt(number)**.5; i+=2){

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


for(i=5;i<=20;i++){

    if(is_prime(i)){

        console.log(i)
    }
}

Aucun commentaire:

Enregistrer un commentaire