Back on the primes for problem 10. Could be an interesting speed issue.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Sounds simple enough. Use the sieve from problem 3 to generate all the primes and then add them up.
It worked! Except it took over a second. A faster prime algorithm is needed.
time passes…
After some significant research, I have a faster prime algorithm. It is known as the RWH algorithm although I don’t know why. I’ve written a Python 3 implementation.
Not the most readable of things, I know.
The strangest bit is in the middle where a subset of a list is assigned to a number of values. This is apparently a thing Python can do. For example:
The precise detail of the calculation is left to the reader, but basically the
extended slice assignment has two parts; the bit being replaced that starts
at i**2
and continues to the end in increments of i
, and the calculation on
the right hand side. This calculation works out how long the slice is without
going to the extent of creating one and calling len()
on it. This is gets a
3x speed boost.
Thanks to the RWH sieve the speed has increased somewhat. The correct answer
of 142913828922
is reached in a mere 138ms
. Better, but not great. I may
revisit later when I get my head around wheel factorisation.
Bonus: Changing the prime generator code has sped problem 7 up from 46ms to a tiny 12ms. Good stuff.