Created
March 26, 2018 20:33
-
-
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.
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
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