VOOZH about

URL: https://www.geeksforgeeks.org/dsa/python-program-for-find-largest-prime-factor-of-a-number/

⇱ Python Program to Find Largest Prime Factor of a Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Program to Find Largest Prime Factor of a Number

Last Updated : 30 Oct, 2025

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.

Output

5

Using primefactors()

Another sympy method is primefactors(), it directly gives a sorted list of all prime factors of a number.

Output

3

Using math Module

This method divides the number continuously by small divisors starting from 2 until only the largest prime factor remains.


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.


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.
Comment
Article Tags:
Article Tags: