Nearest Prime to a number - 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

Example

Following is the code −

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

Following is the output in the console −

29

Updated on: 18-Sep-2020

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements