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.
Here is the same function@Triptych provided as a generator, which has also been simplified slightly.
the max prime can then be found using:
and a list of factors found using:
Similar to @Triptych answer but also different. In this example list or dictionary is not used. Code is written in Ruby
Here's the best algorithm I know of (in Python)
The above method runs in
O(n)
in the worst case (when the input is a prime number).EDIT:
Below is the
O(sqrt(n))
version, as suggested in the comment. Here is the code, once more.All numbers can be expressed as the product of primes, eg:
You can find these by simply starting at 2 and simply continuing to divide until the result isn't a multiple of your number:
using this method you don't have to actually calculate any primes: they'll all be primes, based on the fact that you've already factorised the number as much as possible with all preceding numbers.
I think it would be good to store somewhere all possible primes smaller then n and just iterate through them to find the biggest divisior. You can get primes from prime-numbers.org.
Of course I assume that your number isn't too big :)