What is the best approach to calculating the largest prime factor of a number?
I'm thinking the most efficient would be the following:
- Find lowest prime number that divides cleanly
- Check if result of division is prime
- If not, find next lowest
- Go to 2.
I'm basing this assumption on it being easier to calculate the small prime factors. Is this about right? What other approaches should I look into?
Edit: I've now realised that my approach is futile if there are more than 2 prime factors in play, since step 2 fails when the result is a product of two other primes, therefore a recursive algorithm is needed.
Edit again: And now I've realised that this does still work, because the last found prime number has to be the highest one, therefore any further testing of the non-prime result from step 2 would result in a smaller prime.
There are some modulo tests that are superflous, as n can never be divided by 6 if all factors 2 and 3 have been removed. You could only allow primes for i, which is shown in several other answers here.
You could actually intertwine the sieve of Eratosthenes here:
Also see this question.
Python Iterative approach by removing all prime factors from the number
JavaScript code:
Usage Example:
Here is an example of the code:
I'm aware this is not a fast solution. Posting as hopefully easier to understand slow solution.
Found this solution on the web by "James Wang"