Smallest prime number just greater than the specified number in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 19-Jan-2021 06:13:17
Advertisements