TASK: Sum all the prime numbers up to and including the provided number.
function sumPrimes(num) { var total = 0; // check if n is prime by dividing n for all numbers up to n-1 function isPrime(x) { if (x<2) {return false;} for (y=2; y<x; y++) { if (x%y===0) {return false;} } return true; } //loop through numbers up to num // if they pass the test, add them to the total for (i=num;i>1;i--){ if (isPrime(i)){ total+=i;} } return total; } sumPrimes(10);
Advertisements