简体   繁体   中英

How Can I find the first number greater than const M?

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.

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 .

Simple and fast solution, via prime-lib library (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 start number to be a prime, and if it is - that number is included. 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]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM