Wed 2 Jan 2008
Problem 10 – More prime numbers
Posted by Aaron under ProjectEuler, Python
[7] Comments
So a big part of all this Project Euler nonsense includes prime numbers. Problem 10, begs the ever-so-common question Find the sum of all the primes below one million. Obviously, the first attempt would be to just straight out calculate it using my previous program in Problem 3. Adapting that program to one million integers resulted in about 768 seconds (read: over 10 minutes) of time. Obviously this breaks the 1 minute rule the program needed to be tweaked.
Trying other various methods I still came up short with the result being about 176 seconds at best. To optimize my program I was mainly looking for some information on how prime numbers might be related to bits/bytes to see if I could perhaps try some bitwise operations to speed things up. In doing so, I came across an article suggesting that having an array of bits (essentially a long char) with each char representing a number in an array from 0 to x; x being the limit. Once this array was created, simply just iterate from 0 to the square root of your limit, and mark all multiples of any primes found on your way. Makes sense - and this greatly cuts down on all the harsh prime calculating going on in the background.
(more...)