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 牛年祝福语简短16字
15 古风考试祝福语 唯美简短
16 小朋友六一祝福语简短
17 古文毕业赠言祝福语简短
18 春节祝福语大全简短搞笑