VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-largest-prime-factor-number/

⇱ Find largest prime factor of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find largest prime factor of a number

Last Updated : 17 Feb, 2025

Given a positive integer n ( 1 <= n <= 1015). Find the largest prime factor of a number. 

Input: 6
Output: 3
Explanation Prime factor are 2 and 3. Largest of them is 3.

Input: 15
Output: 5
Explanation: Prime factors are 3 and 5. The largest of them is 5.

Input: 28
Output: 7
Explanation: Prime factors are 2 and 7. The largest of them is 7.

[Naive Approach] Basic Trial Division

  • The method starts by removing all factors of 2, as it is the only even prime.
  • Once 2 is completely removed, odd numbers are checked starting from 3.
  • Each odd number is tested for divisibility, and the number is divided repeatedly until the factor is fully removed.
  • This process continues for all odd numbers up to √n.
  • If a number greater than 2 remains after all divisions, it is a prime number and the largest prime factor.

Output
5

Time complexity: O(sqrt(n)).
Auxiliary space: O(1)

[Expected Approach] Optimized Trial Division

  • The method first removes all factors of 2 and 3 to simplify the number.
  • After eliminating these smallest primes, further factorization follows a structured approach.
  • Instead of checking all odd numbers, only numbers of the form 6k ± 1 are tested.
  • This works because all prime numbers greater than 3 follow this pattern.
  • By skipping unnecessary checks, the approach reduces iterations while efficiently finding the largest prime factor.

Output
5

Time complexity: O(sqrt(n))
Auxiliary space: O(1)


Comment