A prime number is a positive integer greater than 1 that is divisible by only 1 and itself. In other words, a prime number has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers, while 4, 6, 8, and 9 are not (they are all divisible by 2 or 3). The first prime number is 2 and the only even prime number is 2.

A useful fact that can be used to quickly identify a prime number is that, all prime numbers greater than 3 can be represented in the form of 6n ± 1.

Here is a simple example to check if a number is prime using javascript :

function isPrime(num) {
  if (num <= 1) return false;
  if (num <= 3) return true;
  if (num % 2 === 0 || num % 3 === 0) return false;
  for (let i = 5; i * i <= num; i += 6) {
    if (num % i === 0 || num % (i + 2) === 0) {
      return false;
    }
  }
  return true;
}

This function first checks if the number is less than or equal to 1 or 3, in which case it returns false or true respectively. Then it checks if the number is divisible by 2 or 3, if so it returns false. If none of these conditions are met, it uses a for loop to iterate through every number from 5 to the square root of the number and check if the number is divisible by that number or the number + 2. If it is divisible, it returns false. Finally if none of the conditions are met, it returns true.

Note that this function is working for the whole range of JavaScript’s number representation.

Also Read:

Categorized in: