Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements