Wednesday 10 February 2016

Project Euler #3: Largest prime factor


The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
I started off by recycling the code from PE-10. To find the largest prime factor I'm going to find ALL the prime factors. By finding them in increasing order, I'm guaranteed that the last one I find will be the largest prime factor (side note: this also works if the inputted number is a prime number since the factors are 1 and itself).

I begin by setting the limit to the inputted number and starting at 5 and repeating my earlier method to find prime numbers in increasing order (sieving on 2 and 3, then using the idea that the smallest prime factor must be less than or equal to the square root of the number being tested if it's NOT a prime number). For every prime number I test if it's a factor of the inputted number. If it isn't then I store it in my prime number vector and move on. However, if it is then I set the new limit to be the old limit divided by this prime factor. Then I repeat the process. I continue until I reach the limit.

This works only because I'm finding the prime factors in order. Once we find one, we know the next one must be greater or equal to the one we just found. Thus I can continue on in my for-loop, only having to retest the most recent prime number (e.g. 8 is 2x2x2) before moving on. I like this solution because the amount of numbers we test is quite low so it scales really well.

For example, this problem asked for the prime factors of 600851475143. The prime factors are:
  1. 71, new limit is 8462696833
  2. 839, new limit is 10086647
  3. 1471, new limit is 6857
  4. 6857, new limit is 6857 (since they're equal)
Once the latest prime factor equals the limit we know we're done! So we only had to test roughly ~1142 numbers (6857 / 6 since we sieved). I'm not sure if the runtime I measured using is accurate, but it's returning 502 microseconds. I didn't bother making a naive version for this one since I was lazy.

The code can be found here.

No comments:

Post a Comment