Sum All Primes
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes
so it returns the sum of all prime numbers that are less than or equal to num.
注意1不是质数, 2是质数
sumPrimes(10)
should return a number.
Passed
sumPrimes(10)
should return 17.
Passed
sumPrimes(977)
should return 73156.
function sumPrimes(num) {
let map = {}
function isPrime(x) {
for (let i = 2; i < x; i++) {
if (map.hasOwnProperty(x)) {
return map[x]
}
if (x % i === 0) {
map[x] = false
return map[x]
}
}
map[x] = true
return map[x]
}
let prime = []
for (let i = 2; i <= num; i++) {
if (isPrime(i)) {
prime.push(i)
}
}
console.log(prime)
return prime.reduce((x, y) => x + y);
}
console.log(
sumPrimes(10),
sumPrimes(11)
)
hint
https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-sum-all-primes/16085
函数return掉就不会继续执行
关于every
console.log([].every(() => {})) //true
function sumPrimes(num) {
// Check all numbers for primality
let primes = [];
for (let i = 2; i <= num; i++) {
if (primes.every((prime) => i % prime !== 0))
primes.push(i);
}
return primes.reduce((sum, prime) => sum + prime, 0);
}