Javascript Algorithm Number is prime

Description

Javascript Algorithm Number is prime

function isPrime(n){ 
    if (n <= 1) return false; 
    if (n <= 3) return true; 

    // This is checked so that we can skip 
    // middle five numbers in below loop 
    if (n%2 == 0 || n%3 == 0) return false; 

    for (var i=5; i*i<=n; i=i+6){ 
        if (n%i == 0 || n%(i+2) == 0) 
           return false; 
    } //  www .ja  v  a  2  s.  co m

    return true; 
} 

console.log(isPrime(2));
console.log(isPrime(3));
console.log(isPrime(5));

console.log(isPrime(20));



PreviousNext

Related