Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Basic Primality Test Algorithm
The most efficient approach is to check divisibility up to the square root of the number, skipping even numbers after checking for 2.
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)); // First prime
console.log(findPrime(97)); // Large prime
console.log(findPrime(131)); // Another prime
console.log(findPrime(343)); // Composite (7 * 7 * 7)
true true true false
How the Algorithm Works
The function uses several optimizations:
-
Non-integer check:
num % 1 !== 0ensures the input is a whole number - Edge cases: Numbers ? 1 are not prime; 2 and 3 are prime
- Even number check: All even numbers except 2 are composite
- Square root limit: Only check divisors up to ?n since larger factors would have corresponding smaller factors
- Odd divisors only: Skip even divisors after checking 2
Simple Primality Test
Here's a more basic version for educational purposes:
function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
console.log(isPrime(17)); // Prime
console.log(isPrime(25)); // Composite (5 * 5)
console.log(isPrime(29)); // Prime
console.log(isPrime(100)); // Composite
true false true false
Testing Multiple Numbers
const numbers = [2, 3, 4, 5, 17, 25, 97, 100];
numbers.forEach(num => {
console.log(`${num} is ${findPrime(num) ? 'prime' : 'composite'}`);
});
2 is prime 3 is prime 4 is composite 5 is prime 17 is prime 25 is composite 97 is prime 100 is composite
Conclusion
The optimized primality test checks divisibility up to the square root while skipping even numbers, making it efficient for most applications. For very large numbers, more advanced algorithms like Miller-Rabin may be needed.
