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
Selected Reading
Finding nearest prime to a specified number in JavaScript
We are required to write a JavaScript function that takes in a number and returns the first prime number that appears after n.
For example: If the number is 24, then the output should be 29.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const num = 24;
const isPrime = n => {
if (n===1){
return false;
}else if(n === 2){
return true;
}else{
for(let x = 2; x < n; x++){
if(n % x === 0){
return false;
}
}
return true;
};
};
const nearestPrime = num => {
while(!isPrime(++num)){};
return num;
};
console.log(nearestPrime(24));
Output
The output in the console will be −
29
Advertisements
