Javascript Number Integer Sum all prime numbers
// given a number, return the sum of all prime // numbers less than or equal to the number itself /**//w ww. j av a 2s . c o m * @function sumAllPrimes * @param {number} num * @return {number} */ // Using the sieve method function sumAllPrimes(num) { var allPrimes = Array(num+1).fill(true); var i, j; allPrimes[0] = false; allPrimes[1] = false; for (i = 2; i <= parseInt(Math.sqrt(num)); i++) { if (allPrimes[i]) { for (j = i*i; j <= num; j += i) { allPrimes[j] = false; } } } return allPrimes.reduce(function(acc, n, i) { return n ? (i + acc) : acc; }, 0); } console.log('sumAllPrimes(20) => ' + sumAllPrimes(20));