Finding next prime number to a given number using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number n. Our function should that smallest number which is just greater than n and is a prime number.

Example

Following is the code −

 Live Demo

const num = 101;
const isPrime = (num) => {
   let sqrtnum = Math.floor(Math.sqrt(num));
   let prime = num !== 1;
   for(let i = 2; i < sqrtnum + 1; i++){
      if(num % i === 0){
         prime = false;
         break;
      };
   };
   return prime;
}
const nextPrime = (num = 1) => {
   while(!isPrime(++num)){
   };
   return num;
};
console.log(nextPrime(num));

Output

103
raja
Published on 19-Apr-2021 11:11:46
Advertisements