get prime numbers

How to get or check prime numbers in JavaScript?

0 / 0 2 Mins Admin

December 19, 2022

10 Comments

If you want to get the prime numbers up to a given number then here is a function that generates prime numbers in JavaScript:

function getPrimeNumbers(n) {
  // create an array of booleans to represent whether each number is prime or not
  let isPrime = new Array(n + 1).fill(true);

  // set 0 and 1 to not prime
  isPrime[0] = isPrime[1] = false;

  // loop through all the numbers up to n
  for (let i = 2; i <= n; i++) {
    // if the number is prime, mark all its multiples as not prime
    if (isPrime[i]) {
      for (let j = 2 * i; j <= n; j += i) {
        isPrime[j] = false;
      }
    }
  }

  // create an array to store the prime numbers
  let primes = [];

  // loop through the isPrime array and add the prime numbers to the primes array
  for (let i = 0; i <= n; i++) {
    if (isPrime[i]) {
      primes.push(i);
    }
  }

  return primes;
}

To use the function, you can call it with a number n as an argument, like this:

let primeNumbers = getPrimeNumbers(20);
console.log(primeNumbers); 

// [2, 3, 5, 7, 11, 13, 17, 19]

This will generate an array of all the prime numbers up to n. In this case, the output will be an array containing prime numbers from 2 to 20.

How to Check Prime Number in JavaScript?

You can also check if a number is prime in JavaScript, you can use the following function:

function isPrime(n) {
  // check if n is less than 2
  if (n < 2) {
    return false;
  }

  // loop through the numbers from 2 to the square root of n
  for (let i = 2; i <= Math.sqrt(n); i++) {
    // if n is divisible by i, it is not prime
    if (n % i === 0) {
      return false;
    }
  }

  // if the loop finishes, n is prime
  return true;
}

Now call the function isPrime(number) to test a number if it is a prime or not. To use the above function, you can call it with a number as an argument, like this:

console.log(isPrime(2)); // true
console.log(isPrime(3)); // true
console.log(isPrime(4)); // false
console.log(isPrime(19)); // true

This function uses a loop to check if the number is divisible by any other number between 2 and the square root of the number. If the number is not divisible by any of these numbers, it is considered prime.