范围内的素数之和 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/7 5:00:17
我们需要编写一个 JavaScript 函数,该函数接受两个数字,例如 a 和 b,并返回 a 和 b 之间所有素数之和。如果 a 和 b 也是素数,则应包括它们。
示例
以下是代码 −
const num1 = 45;
const num2 = 345;
const isPrime = n => {
if (n===1){
return false;
}else if(n === 2){
return true;
}else{
for(let x = 2; x < n; x++){
if(n % x === 0){
return false;
}
}
return true;
};
};
const primeBetween = (a, b) => {
const res = [];
while(a <= b){
if(isPrime(a)){
res.push(a);
};
a++;
};
return res;
};
console.log(primeBetween(num1, num2));
输出
以下是控制台中的输出 −
[ 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

