Sum All Primes
1. Requirements
- Sum of prime numbers less than or equal to a given number.
- Only 1 and its own two approximate numbers are called prime numbers. For example, 2 is a prime number, because it can only be divisible by 1 and 2. 1 is not a prime number because it can only be divisible by itself.
2. Ideas
- To define the mark variable in a loop starting from 3 to no more than NUM, initially true
- Determines whether I is a prime number in a two-layer cycle, no, turns mark to False
- The end of a layer of loops when mark is true, adds a prime number that is less than or equal to a given value.
3. Code
function sumPrimes(num) { var arr = [2]; var newNum = 2; for (var i=3; i<=num; i++){ var mark = true; for (var j=0; j<arr.length; j++){ if(i%arr[j] === 0){ mark = false; } } if(mark){ arr.push(i); newNum += i; } } return newNum;//本代码只计算num大于2的情况}sumPrimes(9);
4. RELATED LINKS
- Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for
- Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Sum All Primes-freecodecamp Algorithm topic