Riddle 10: Summation of primes

Riddle 10: Summation of primes


1 min read

The Task

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

This task is so easy that it is almost not worth its own post. The reason is because it is identical to Task 7, "10001st prime" except that we need to add one single line.

The solution

What we need to do is:

  1. Generate a list of all prime numbers below 2.000.000,
  2. Sum up all list items.

For 1., we can re-use the code from Task 7 without modification. The only challenge is that instead of 10.000 prime numbers, we need to calculate around 150.000 prime numbers. Then we sum all list items up with apply:

(load "./Task_7_10001_Prime_final.l")
(prinl (apply + (sieve 2000000)))

Let's compare the computation time for Task 7 and Task 10.

: (bench (apply + (sieve 110000)))
0.114 sec
-> 544815056
: (bench (apply + (sieve 2000000)))
5.135 sec
-> 142913828922

The computation time has increased from 0.1 s to 5.1 s, but is still much faster than the 60 seconds that the task description allows.

You can find the "code" for the finished task here.