JavaScript中所有质数的总和
我们需要编写一个以数字作为唯一参数的JavaScript函数。该函数应找到并返回所有小于n的质数的和。
例如-
如果n=10,则输出应为17,因为最多10的质数为2、3、5、7,其和为17
示例
为此的代码将是-
const isPrime = (num) => {
let x = Math.floor(Math.sqrt(num));
let j = x;
while (j >= 2) {
if (num % j === 0) {
return false;
}
j−−;
}
return true;
};
const sumOfPrimes = (num = 10) => {
let iter = num;
let sum = 0;
while (iter >= 2) {
if (isPrime(iter) === true) {
sum += iter;
}
iter−−;
}
return sum;
};
console.log(sumOfPrimes(14));
console.log(sumOfPrimes(10));输出结果
控制台中的输出将是-
41 17 1060
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短