Monday, 21 March 2011

Prime Factors - Comment on the logic

There are a few things that need to be mentioned about the logic of my prime factors program.

The first is that for simplicity I have just incremented the prime factor variable X by one each time, so when X is 3, the next prime factor to be tried is 4. Clearly, 4 is not a prime number and so it is ineffecient to be using this number (the same is also true of 6, 8, 9, 10...etc.). However, it does not cause a problem with the logic, it just means that the program takes longer to run. I will address this issue again later.

Secondly, I have stopped the program when the square of the prime factor variable X is larger than the number A that we are testing. Why is this? Well, suppose our number is 63 and we have found the prime factors, 3, 3 and 7. We might try and see if the next prime number 11 is a factor of 63, but 63 divided by 11 is about 5.7. So we would already have found the factor 5 (if it was a factor) when looking for factors between 3 and 7. So in our test to see where to stop searching for prime factors we note that 7 squared is 49 (which is less than 63) and 11 squared is 121 (which is greater than 63), so it is clear that we can stop our prime factor search at 7.

Finally, we note that it would be much more efficient to use division than multiples of prime factors. For example, 63 divided by 2 gives 31 remainder 1. 63 divided by 3 gives 21 remainder zero. So, if we had knew the remainder, we could easily determine whether 2, 3, ... etc were factors or not. Unfortunately, the fx-50F is missing this functionality and so we have had to restort to using multiples of prime factors.

No comments:

Post a Comment