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 check
Check if
divisible by any number from up to . Check the reminder of each number upto
. If reminder of all the numbers upto
is zero, then number is not prime. Otherwise, it is prime.
//Prime number is implementationfunction 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 primeconsole.log(checkPrime(2)); //trueconsole.log(checkPrime(3)); //trueconsole.log(checkPrime(4)); //falseconsole.log(checkPrime(5)); //trueconsole.log(checkPrime(7)); //trueconsole.log(checkPrime(8)); //falseconsole.log(checkPrime(11)); //true
Explanation
Let’s discuss the code above in detail.
Line 2: Define the
checkPrimefunction that takesnas an input parameter.Lines 4–6: Check if a
nis less than or equal to1. If the condition is true, we returnfalsevalue as it is not a prime number. Otherwise, theelsestatement will execute.Lines 8–15: Use the
forloop to check reminders of each number from2to upton/2. If thenis 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