How do I check if a value is a prime number in JavaScript?
Alex K
alex k profile pic

To check if a value is a prime number in JavaScript, you can use the following approach: 1. Handle edge cases: - Check if the value is less than 2 because prime numbers are defined as integers greater than 1. - If the value is less than 2, returnfalse since it cannot be a prime number. 2. Iterate through potential divisors: - Start a loop from 2 and continue until the square root of the value, because divisors larger than the square root will have corresponding divisors smaller than the square root. - Check if the value is divisible evenly by any number within this range. - If a divisor is found, returnfalse as the value is not a prime number. - If no divisor is found within the range, the value is a prime number. Here's an example implementation:

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

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

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

  return true;
}

console.log(isPrime(7)); // Output: true
console.log(isPrime(10)); // Output: false
console.log(isPrime(17)); // Output: true
console.log(isPrime(25)); // Output: false

In this example, theisPrime() function checks if a given value is a prime number. It first handles the edge case where the value is less than 2. Then, it iterates from 2 to the square root of the value and checks if the value is divisible evenly by any number within this range. If a divisor is found, the function returnsfalse. Otherwise, if no divisor is found, it returnstrue indicating that the value is a prime number. Note that this implementation works efficiently for relatively small numbers. However, for very large numbers, more advanced algorithms such as the Sieve of Eratosthenes or the Miller-Rabin primality test may be more suitable.