Given a positive integer n (1 ≤ n ≤ 1015), the task is to find its largest prime factor the biggest prime number that divides n exactly. For Example:
Input: n = 6
Output: 3
Explanation: prime factors of 6 are 2 and 3, and the largest among them is 3.
Let's explore different methods to find largest prime factor of a number in Python.
Using factorint()
sympy provides the function factorint() which directly returns all prime factors of a number and their powers, and using max() we can extract the largest number.
from sympy import factorint
n = 15
factors = factorint(n)
print(max(factors))
Output
5
Using primefactors()
Another sympy method is primefactors(), it directly gives a sorted list of all prime factors of a number.
from sympy import primefactors
n = 18
print(max(primefactors(n)))
Output
3
Using math Module
This method divides the number continuously by small divisors starting from 2 until only the largest prime factor remains.
import math
n = 34
max_prime = -1
while n % 2 == 0:
max_prime = 2
n //= 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
max_prime = i
n //= i
if n > 2:
max_prime = n
print(max_prime)
Output
17
Explanation:
- math.sqrt() limits checks up to √n for efficiency.
- Removes all factors of 2 first, then tests odd divisors.
- Each valid divisor updates max_prime.
- Any leftover number > 2 is the largest prime factor.
Using Iterative Division
This method does not use any external modules. It uses a loop that keeps dividing the number by its smallest divisor until all smaller factors are removed.
n = 45
i = 2
res = -1
while i * i <= n:
while n % i == 0:
res = i
n //= i
i += 1
if n > 1:
res = n
print(res)
Output
5
Explanation:
- The loop runs while i*i is less than or equal to n, ensuring all possible factors are checked.
- When a divisor divides n, it is recorded and removed completely.
- The loop increments i to check for the next factor.
- After all smaller factors are removed, the leftover number (if greater than 1) is the largest prime factor.