print prime numbers in javascript 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: hwo to make ana array of prime numbers in javascript

function sort_prime(num) {

  var prime_num1 = [],
      prime_num2 = [];
  for (var i = 0; i <= num; i++) {
    prime_num2.push(true);
  }
  for (var i = 2; i <= num; i++) {
    if (prime_num2[i]) {
      prime_num1.push(i);
      for (var j = 1; i * j <= num; j++) {
        prime_num2[i * j] = false;
      }
    }
  }

  return prime_num1;
}

console.log(sort_prime(5))

Example 4: javascript write all the prime numbers from 1 to 100

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

function display(n) {
    var arr = [2];
    for ( var i = 3; i < n; i+=2 ) {
        if ( isPrime(i) ) {
            arr.push(i);
        }
    }
    console.log(arr); // use arr result on your own
}

display(100);


//Added Functionality

function prime(n,flag) {
    ( typeof flag === "undefined" || flag === false ) ? flag = false : flag = true;

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

    if ( flag ) {
        var arr = [2];
        for ( var i = 3; i <= n; i+=2 ) {
            if ( isPrime(i) ) {
                arr.push(i);
            }
        }
        return arr;
    } else {
        return isPrime(n);
    }
}