prime numbers in js 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: javascript find prime number

function test_prime(n){
  if (n===1) {
    return false;
  }else if(n === 2){
    return true;
  }else{
    for(var x = 2; x < n; x++){
      if(n % x === 0){
        return false;
      }
    }
    return true;  
  }
}

console.log(test_prime(37));

Example 4: Prime number function Js

// program to check if a number is prime or not
function isPrime(){
    // take input from the user
    const number = parseInt(prompt("Enter a positive number: "));
    let isPrime = true;

    // check if number is equal to 1
    if (number === 1) {
        console.log("1 is neither prime nor composite number.");
    }

    // check if number is greater than 1
    else if (number > 1) {

        // looping through 2 to number-1
        for (let i = 2; i < number; i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            console.log(`${number} is a prime number`);
        } else {
            console.log(`${number} is a not prime number`);
        }
    }

    // check if number is less than 1
    else {
        console.log("The number is not a prime number.");
    }
}