Finding next prime number to a given number using JavaScript


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

Updated on: 19-Apr-2021

932 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements