js check if prime number code example

Example 1: javascript find a prime number

// This seems to be the most common and comprehensive means
// of implementing a 'is a number a prime function' in javascript 
// if you would like t0 learn more complex , but efficient algorithms. 
// Visit the link below
// https://stackoverflow.com/questions/11966520/how-to-find-prime-numbers-between-0-100

function isPrime(num) {
  if(num < 2) return false;

  for (let k = 2; k < num; k++){
    if( num % k == 0){
      return false;
    }
  }
  return true;
}

Example 2: prime numbers javascript

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

Example 3: prime or not in javascript

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

Example 4: js code to check whether a number is prime or not

function isPrime(n)
{
    if (n < 2)
        return false;
        
    if (n == 2)
        return true;
    
    var maxDiv = Math.sqrt(n);
    
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    
    return true;
}

println(2, " is prime? ", isPrime(2));
println(3, " is prime? ", isPrime(3));
println(4, " is prime? ", isPrime(4));
println(5, " is prime? ", isPrime(5));
println(9, " is prime? ", isPrime(9));

Example 5: Javascript prime number check

// 6k+-1 optimisation
function is_prime (n) {
  if (n < 3) return n > 1;
  else if (n % 2 === 0 || n % 3 === 0) return false;
  else if (n < 25) return true;
  let i = 5;
  while (i * i <= n ) {
    if (n % i === 0 || n % (i + 2) === 0) return false;
    i += 6;
  }
  return true;
}