在 JavaScript 中生成随机素数
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,该函数接受两个指定范围的数字。我们的函数应该返回一个落在该范围内的随机素数
示例
其代码为 −
const range = [100, 1000];
const getPrimes = (min, max) => {
const result = Array(max + 1)
.fill(0)
.map((_, i) => i);
for (let i = 2; i <= Math.sqrt(max + 1); i++) {
for (let j = i ** 2; j < max + 1; j += i) delete result[j];
}
return Object.values(result.slice(min));
};
const getRandomNum = (min, max) => {
return Math.floor(Math.random() * (max − min + 1) + min);
};
const getRandomPrime = ([min, max]) => {
const primes = getPrimes(min, max);
return primes[getRandomNum(0, primes.length − 1)];
};
console.log(getRandomPrime(range));
输出
控制台中的输出将是 −
311
每次运行的输出可能会有所不同。
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

