[英]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?我必须找到第一个大于我的 const M 的素数。例如,我有 M = 11,我必须找到第一个大于 M 的素数,它是 13。我该怎么做?
// 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.我想找到 M = 11、primeNumber = 13、M = 15、primeNumber = 17 等。
You can iterate from M+1
until you find your prime number.您可以从M+1
迭代,直到找到您的素数。 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).简单快速的解决方案,通过prime-lib库(我是作者)。
The example below generates 2 primes, starting with 7 and upward:下面的示例生成 2 个素数,从 7 开始及以上:
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.它检查start
数字是否为素数,如果是,则包括该数字。 If you need only a prime that follows, just check if the first number matches your M
number, then take the next one instead:如果您只需要一个素数,只需检查第一个数字是否与您的M
数字匹配,然后取下一个数字:
if(values[0] === M) {
// use values[1]
} else {
// use values[0]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.