2

I have a problem with this. I have to find the first prime number greater than my const M. For example, I have M = 11, and I have to find the first prime number greater than M and it is 13. How Can I do that?

// isPrime

const M = 11

function isPrime(num) {
  if (num < 2) return false;
  for (let i = 2; i < num; i++) {
    if (num % i == 0) return false;
  }
  return true;
}

console.log(isPrime(M))

And I would like find for M = 11, primeNumber = 13, for M = 15, primeNumber = 17 etc.

Manas Khandelwal
  • 3,515
  • 2
  • 10
  • 22

2 Answers2

1

You can iterate from M+1 until you find your prime number. You can do the following,

function isPrime(num) {
    if (num < 2) return false;
    for (let i = 2; i < num; i++) {
        if (num % i == 0) return false;
    }
    return true;
}

findGreaterPrime = (m) => {
  let i = m+1;
  let found = false;
  while(!found) {
    if(isPrime(i)) {
      found = true;
      return i;
    }
    i++;
  }
}

console.log(findGreaterPrime(11));
console.log(findGreaterPrime(13));

By the way, this method will be very slow for larger numbers. You can use some fast prime generators. You can follow the answers in this thread.

Md Sabbir Alam
  • 4,709
  • 3
  • 13
  • 27
1

Simple and fast solution, via prime-lib (I'm the author).

The example below generates 2 primes, starting with 7 and upward:

import {generatePrimes, stopOnCount} from 'prime-lib';

const i = generatePrimes({start: 7}); // infinite prime-iterator
const s = stopOnCount(i, 2); // stop-iterator

const values = [...s]; // 7, 11

It checks if start is a prime, to be included then. If you need only a prime that follows, just check if the first number matches your M number, then take the next one instead:

if(values[0] === M) {
   // use values[1]
} else {
   // use values[0]
}
vitaly-t
  • 22,286
  • 10
  • 106
  • 127