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.
Compute a list storing prime numbers first, e.g. 2 3 5 7 11 13 ...
Every time you prime factorize a number, use implementation by Triptych but iterating this list of prime numbers rather than natural integers.
With Java:
For
int
values:For
long
values:Calculates the largest prime factor of a number using recursion in C++. The working of the code is explained below:
I am using algorithm which continues dividing the number by it's current Prime Factor.
My Solution in python 3 :
Input :
10
Output :5
Input :
600851475143
Output :6857
Prime factor using sieve :
The simplest solution is a pair of mutually recursive functions.
The first function generates all the prime numbers:
The second function returns the prime factors of a given number
n
in increasing order.n
.The largest prime factor of
n
is the last number given by the second function.This algorithm requires a lazy list or a language (or data structure) with call-by-need semantics.
For clarification, here is one (inefficient) implementation of the above in Haskell:
Making this faster is just a matter of being more clever about detecting which numbers are prime and/or factors of
n
, but the algorithm stays the same.