Last active
June 15, 2018 17:55
-
-
Save eday69/c7cbe6a94b2e2f53cc7192d52af94078 to your computer and use it in GitHub Desktop.
freeCodeCamp Intermediate Algorithm Scripting: Sum All Primes
This file contains hidden or 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
// 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) { | |
let ourSum=0; // We start with one, prime for 1 | |
for (let i=2; i<=num; i++) { | |
let prime=true; | |
for (let j=2; j<=Math.sqrt(i); j++) { | |
if ((i % j) == 0) { | |
prime=false; | |
break; | |
} | |
} | |
if (prime) { | |
ourSum+=i; | |
} | |
} | |
return ourSum; | |
} | |
sumPrimes(10); // 17 | |
sumPrimes(977); // 73156 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment