Created
July 6, 2017 07:22
-
-
Save karlwills/47bcea801091f24d2c3e1e3dd2ca9699 to your computer and use it in GitHub Desktop.
Sum all primes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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