https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes


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.

  1. function sumPrimes(num) {
  2. let map = {}
  3. function isPrime(x) {
  4. for (let i = 2; i < x; i++) {
  5. if (map.hasOwnProperty(x)) {
  6. return map[x]
  7. }
  8. if (x % i === 0) {
  9. map[x] = false
  10. return map[x]
  11. }
  12. }
  13. map[x] = true
  14. return map[x]
  15. }
  16. let prime = []
  17. for (let i = 2; i <= num; i++) {
  18. if (isPrime(i)) {
  19. prime.push(i)
  20. }
  21. }
  22. console.log(prime)
  23. return prime.reduce((x, y) => x + y);
  24. }
  25. console.log(
  26. sumPrimes(10),
  27. sumPrimes(11)
  28. )

hint

https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-sum-all-primes/16085

函数return掉就不会继续执行

关于every

  1. console.log([].every(() => {})) //true
  1. function sumPrimes(num) {
  2. // Check all numbers for primality
  3. let primes = [];
  4. for (let i = 2; i <= num; i++) {
  5. if (primes.every((prime) => i % prime !== 0))
  6. primes.push(i);
  7. }
  8. return primes.reduce((sum, prime) => sum + prime, 0);
  9. }