Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 26, 2018 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/ad828a13b38155bcac3f56488a84f2a8 to your computer and use it in GitHub Desktop.
Save nickihastings/ad828a13b38155bcac3f56488a84f2a8 to your computer and use it in GitHub Desktop.
Sum all the prime numbers up to and including the provided number. 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. The provided number may not be a prime.
function sumPrimes(num) {
var ints = [2]; //array to hold prime numbers
//function to test if a number is a prime
function isPrime(test){
for(var i = 2; i < test; i++){
if(test % i == 0){ //if there's no remainder it's not a prime
return false; //not a prime number
}
}
return true;
}
//get all numbers below num that are prime and push to the array
for(var j = 3; j <= num; j++){
if( isPrime(j) ){
ints.push(j);
}
}
//reduce the array to a single total by adding all prime numbers
var sumPrimes = ints.reduce(function(total, current){
return total + current;
});
return sumPrimes;
}
sumPrimes(10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment