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.
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.
There are multiple ways to solve this problem, but we’ll use the following approach to check
Check if
Check the reminder of each number upto
If reminder of all the numbers upto
//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
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: