Условие
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.
Ограничения
2 ≤ n ≤ 10¹². The input 1 is excluded because it has no prime factor.
Примеры
Ввод:
n = 84
Ожидаемый вывод:
expected = 7
Ввод:
long long n = 84;
Ожидаемый вывод:
long long expected = 7;
Ввод:
long n = 84;
Ожидаемый вывод:
long expected = 7;
Пояснение
84 = 2 × 2 × 3 × 7, so the largest prime factor is 7.
Ввод:
n = 13
Ожидаемый вывод:
expected = 13
Ввод:
long long n = 13;
Ожидаемый вывод:
long long expected = 13;
Ввод:
long n = 13;
Ожидаемый вывод:
long expected = 13;
Пояснение
13 is prime, so it is its own largest prime factor.
Как подступиться
Сначала попробуйте сами, затем открывайте подсказки по одной.
Подсказка 1
Remove small prime factors first; any remaining value can only shrink, and the last factor left is the answer.
Подсказка 2
Test divisors only up to the square root of the current remainder, and divide it out repeatedly when it fits.
Подсказка 3
If the remainder is still above 1 after checking smaller factors, that remainder is prime and is the largest factor.
Ожидаемая сложность
O(√n) time, O(1) extra space
Ссылки
Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.