Back to challenges
Medium 0 solved 0% acceptance

Largest Prime Factor

Find the largest prime that divides a positive integer.

What you'll learn

  • Divide out factors from smallest to largest
  • Stop at the square root of what is left
  • Handle large numbers efficiently

Problem

A prime is an integer greater than 1 with no positive divisors other than 1 and itself. Find the largest prime factor of n. When n is itself prime, return n.

Implement largest_prime_factor(n).

Input

n: The integer to factor.

Output

Return its largest prime divisor.

Constraints

2 ≤ n ≤ 10¹². The input 1 is excluded because it has no prime factor.

Examples

Example 1
Input:
n = 84

Expected output:
expected = 7
Input:
long long n = 84;

Expected output:
long long expected = 7;
Input:
long n = 84;

Expected output:
long expected = 7;

Explanation

84 = 2 × 2 × 3 × 7, so the largest prime factor is 7.

Example 2
Input:
n = 13

Expected output:
expected = 13
Input:
long long n = 13;

Expected output:
long long expected = 13;
Input:
long n = 13;

Expected output:
long expected = 13;

Explanation

13 is prime, so it is its own largest prime factor.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Remove small prime factors first; any remaining value can only shrink, and the last factor left is the answer.

Hint 2

Test divisors only up to the square root of the current remainder, and divide it out repeatedly when it fits.

Hint 3

If the remainder is still above 1 after checking smaller factors, that remainder is prime and is the largest factor.

Expected complexity

O(√n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.