Skip to content

Instantly share code, notes, and snippets.

@karlwills
Created July 6, 2017 07:22
Show Gist options
  • Save karlwills/47bcea801091f24d2c3e1e3dd2ca9699 to your computer and use it in GitHub Desktop.
Save karlwills/47bcea801091f24d2c3e1e3dd2ca9699 to your computer and use it in GitHub Desktop.
Sum all primes
/*
A prime number is defined as a number greater than one and having only two divisors,
one and itself. For example, 2 is a prime number because it's only divisible
by one and two.
*/
function getPrimes(max) {
var sieve = [];
var primes = [];
var i;
var j;
for (i = 2; i <= max; i++) {
if (!sieve[i]) {
primes.push(i);
}
for (j = i << 1; j <= max; j+= i) {
sieve[j] = true;
}
}
return primes;
}
function sumPrimes(num) {
if (num < 2) return 'Please enter a number more than 2';
return getPrimes(num).reduce(function(a, b) {
return a + b;
}, 0);
}
sumPrimes(977);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment