How to check if a number is prime in JavaScript

A prime number is a number that should be greater than 1 and divisible by 1 and itself only. Prime numbers are beneficial in secure digital communication, play a vital role in encryption, and act as a building block in solving various mathematical and programming problems.

Goal

In this Answer, our goal is to find whether a given number is prime or not as illustrated in the given table below.

Number

Divisible By

Prime?

2

1,2

Yes

3

1,3

Yes

4

1,2,4

No

5

1,5

Yes

6

1,2,3,6

No

7

1,7

Yes

Prime numbers are mostly odd numbers except 2, which is the only even prime number. Both 2 and 3 are the only two consecutive integers prime in number counting.

Code example

There are multiple ways to solve this problem, but we’ll use the following approach to checkNNis prime or not:

  • Check ifNNdivisible by any number from 22 up to n/2n / 2.

  • Check the reminder of each number upto n/2n/2.

  • If reminder of all the numbers upto n/2n/2 is zero, then number is not prime. Otherwise, it is prime.

//Prime number is implementation
function checkPrime (n) {
if (n <= 1)
{
return false;
}
else
{
let m=2;
while(m <= n/2)
{
if((n%m) == 0)
{
return false;
}
m++;
}
return true;
}
}
//check if the number is prime
console.log(checkPrime(2)); //true
console.log(checkPrime(3)); //true
console.log(checkPrime(4)); //false
console.log(checkPrime(5)); //true
console.log(checkPrime(7)); //true
console.log(checkPrime(8)); //false
console.log(checkPrime(11)); //true

Explanation

Let’s discuss the code above in detail.

  • Line 2: Define the checkPrime function that takes n as an input parameter.

  • Lines 4–6: Check if a n is less than or equal to 1. If the condition is true, we return false value as it is not a prime number. Otherwise, the else statement will execute.

  • Lines 8–15: Use the for loop to check reminders of each number from 2 to upto n/2. If the n is divisible by all numbers, then it is not prime, return false (e.g., for input number 4). Otherwise, it returns true.

As we’ve seen in this Answer, determining whether a number is prime is a straightforward task in JavaScript. This foundational skill allows for confidently and easily exploring diverse applications and problem-solving scenarios.

If you want to learn this task in different languages such as C++, Python, Java, or Dart. Please visit the following Answers on our platform:

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved