Volver a los desafíos
Intermedio 0 resueltos 0% de aceptación

Largest Prime Factor

Find the largest prime that divides a positive integer.

Lo que aprenderás

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

Problema

Ver traducción

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.

Restricciones

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

Ejemplos

Ejemplo 1
Entrada:
n = 84

Salida esperada:
expected = 7
Entrada:
long long n = 84;

Salida esperada:
long long expected = 7;
Entrada:
long n = 84;

Salida esperada:
long expected = 7;

Explicación

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

Ejemplo 2
Entrada:
n = 13

Salida esperada:
expected = 13
Entrada:
long long n = 13;

Salida esperada:
long long expected = 13;
Entrada:
long n = 13;

Salida esperada:
long expected = 13;

Explicación

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

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

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

Pista 2

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

Pista 3

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

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.