One Pager Cheat Sheet
- Write a method
sumOfAllPrimes
that takes a numbern
and returns the sum of all prime numbers smaller than or equal ton
. - We can use an array of length
n+1
initialized with natural numbers starting from 2, and removing 0 and 1, to programmatically determine what numbers are prime. - We can figure out the prime number candidates that are smaller than
n
with anO(n^2)
operation by looping through every number from2
to the current one and seeing if it is divisible. - We can check for prime numbers efficiently by looping over the numbers below
n
and performing alog n
time operation to check divisibility by prime numbers larger than the square root ofn
. - We can use a filter that requires a number to be divisible beyond its square root in order to determine if it is a prime number, which allows us to efficiently find and sum all prime numbers.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
44
}
var assert = require('assert');
function sumOfPrimes(n) {
const numsLessThanN = Array.from({ length: n + 1 }, function (val, idx) {
return idx;
}).slice(2);
const primes = numsLessThanN.filter((num) => {
let primeCandidate = num - 1;
while (primeCandidate > 1 && primeCandidate >= Math.sqrt(num)) {
if (num % primeCandidate === 0) return false;
primeCandidate--;
}
return true;
});
return primes.reduce((prime1, prime2) => prime1 + prime2);
}
try {
assert.deepEqual(2, sumOfPrimes(2), 'sumOfPrimes(2) should equal 2');
console.log('PASSED: ' + '`sumOfPrimes(2)` should equal `2`');
} catch (err) {
console.log(err);
}
try {
assert.deepEqual(129, sumOfPrimes(30), 'sumOfPrimes(30) should equal 129');
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.