prime number in javascript

To check if a number is prime or not in JavaScript, we can use the following algorithm:

  1. Check if the number is less than 2. If it is, return false.

  2. Loop through all the numbers from 2 to the square root of the given number.

  3. If the given number is divisible by any of these numbers, return false.

  4. Otherwise, return true.

Here's the corresponding JavaScript code:

index.tsx
function isPrime(num) {
  if (num < 2) {
    return false;
  }
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return true;
}
181 chars
12 lines

This function takes a number num as input and returns true if it is prime, and false otherwise.

To use this function, simply call it with the number you want to check:

index.tsx
console.log(isPrime(5)); // true
console.log(isPrime(10)); // false
68 chars
3 lines

gistlibby LogSnag