How do I check if a value is a prime number in JavaScript efficiently?
Gable E
gable e profile pic

To efficiently check if a value is a prime number in JavaScript, you can use various optimized algorithms. Here's one approach using trial division: 1. First, handle special cases: - If the number is less than 2, it is not prime. - If the number is 2 or 3, it is prime. 2. Iterate from 2 to the square root of the number (inclusive): - Check if the number is divisible by any integer within this range. - If it is divisible by any number, it is not prime. - If no divisors are found, it is prime. Here's the JavaScript code for this algorithm:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

function isPrime(number) {
  if (number < 2) {
    return false;
  }

  if (number === 2 || number === 3) {
    return true;
  }

  const sqrt = Math.sqrt(number);
  for (let i = 2; i <= sqrt; i++) {
    if (number % i === 0) {
      return false;
    }
  }

  return true;
}

This algorithm has a time complexity of approximately O(sqrt(n)). By iterating up to the square root of the number, we reduce the number of division operations needed, making it more efficient than checking divisibility up to the number itself. You can use theisPrime() function to check if a given value is a prime number. It will returntrue if the number is prime andfalse otherwise. Keep in mind that this algorithm is efficient for smaller numbers. If you need to work with extremely large numbers, you may need to consider more advanced prime number algorithms, such as the Miller-Rabin primality test or the Sieve of Eratosthenes.