One Pager Cheat Sheet

  • Write a method sumOfAllPrimes that takes a number n and returns the sum of all prime numbers smaller than or equal to n.
  • 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 an O(n^2) operation by looping through every number from 2 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 a log n time operation to check divisibility by prime numbers larger than the square root of n.
  • 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.

JAVASCRIPT

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.