모든 챌린지
보통 2명 해결 정답률 28.6%

Largest Prime Factor

Find the largest prime that divides a positive integer.

배우게 될 내용

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

문제

번역본 보기

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.

예시

예시 1
입력:
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.

예시 2
입력:
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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 ННикита Python 949 ms - 4/5 코드 보기
2 KKKaneki Ken Python 1,000 ms - 3/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 솔루션

스포일러: 아래에 2개 전체 솔루션 있음 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.