Primality test of numbers in JavaScript


A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. All other natural numbers greater than 1 are called composite numbers. A primality test is an algorithm for determining whether an input number is prime.

We are required to write a JavaScript function that takes in a number and checks whether it is a prime or not.

Example

Following is the code −

const findPrime = (num = 2) => {
   if (num % 1 !== 0) {
      return false;
   }
   if (num <= 1) {
      return false;
   }
   if (num <= 3) {
      return true;
   }
   if (num % 2 === 0) {
      return false;
   }
   const dividerLimit = Math.sqrt(num);
   for (let divider = 3; divider <= dividerLimit; divider += 2) {
      if (num % divider === 0) {
         return false;
      }
   }
   return true;
};
console.log(findPrime(2));
console.log(findPrime(97));
console.log(findPrime(131));
console.log(findPrime(343));

Output

Following is the output on console −

true
true
true
false

Updated on: 11-Dec-2020

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements