Smallest prime number just greater than the specified number in JavaScript


We are required to write a JavaScript function that takes in a positive integer as the first and the only argument.

The function should find one such smallest prime number which is just greater than the number specified as argument.

For example −

If the input is −

const num = 18;

Then the output should be:

const output = 19;

Example

Following is the code:

const num = 18;
const justGreaterPrime = (num) => {
   for (let i = num + 1;; i++) {
      let isPrime = true;
      for (let d = 2; d * d <= i; d++) {
         if (i % d === 0) {
            isPrime = false;
            break;
         };
      };
      if (isPrime) {
         return i;
      };
   };
};
console.log(justGreaterPrime(num));

Output

Following is the console output −

19

Updated on: 19-Jan-2021

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements