Monday 11 April 2011

Prime Factors - increasing efficiency

Previously I mentioned that for simplicity I have just incremented the prime factor variable X in my program by one each time, so when X is 3, the next prime factor to be tried is 4. As I said then, clearly 4 is not a prime number and so it is ineffecient to be using this number in the search for prime factors (the same is also true of 6, 8, 9, 10...etc.).

So, how could this be improved? Well, the answer is to add some logic like this after incrementing X:-

If X=4 then
   X=X+1
If-End

So this will mean that 4 is skipped and the next prime number that is tried is 5. A similar approach can be used when X=6 (the next prime being 7), but at X=8 we need to add 3 as the next prime number is 11.

I will leave it to the reader to make these adjustments to their code.