What is the best approach to calculating the largest prime factor of a number?
I'm thinking the most efficient would be the following:
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.
Factors are numbers that completely divide a particular number to get zero as a remainder. For example, if we look at the number 6 , it has four factors: 1 , 2 , 3 , 6 . However, of these factors, 2 and 3 are prime numbers. As 3 is greater than 2 , 3 is said to be the largest prime factor of number 6 .
Prime Factor− In number theory, the prime factors of a positive integer are the prime numbers that divide that integer exactly. The process of finding these numbers is called integer factorization, or prime factorization. Input: n = 124 Output: 31 is the largest prime factor!
To find this, the following algorithm can be used: number = num Step 1: If num is divisible by 2, store largest prime factor as 2. keep on dividing num until it is not divisible by 2. After each division, update num as num/2.
Here's the best algorithm I know of (in Python)
def prime_factors(n): """Returns all the prime factors of a positive integer""" factors = [] d = 2 while n > 1: while n % d == 0: factors.append(d) n /= d d = d + 1 return factors pfs = prime_factors(1000) largest_prime_factor = max(pfs) # The largest element in the prime factor list
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.
def prime_factors(n): """Returns all the prime factors of a positive integer""" factors = [] d = 2 while n > 1: while n % d == 0: factors.append(d) n /= d d = d + 1 if d*d > n: if n > 1: factors.append(n) break return factors pfs = prime_factors(1000) largest_prime_factor = max(pfs) # The largest element in the prime factor list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With