Trung bình 2 đã giải Tỷ lệ chấp nhận 28.6%

Largest Prime Factor

Find the largest prime that divides a positive integer.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
n = 84

Kết quả mong đợi:
expected = 7
Đầu vào:
long long n = 84;

Kết quả mong đợi:
long long expected = 7;
Đầu vào:
long n = 84;

Kết quả mong đợi:
long expected = 7;

Giải thích

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

Ví dụ 2
Đầu vào:
n = 13

Kết quả mong đợi:
expected = 13
Đầu vào:
long long n = 13;

Kết quả mong đợi:
long long expected = 13;
Đầu vào:
long n = 13;

Kết quả mong đợi:
long expected = 13;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 ННикита Python 949 ms - 4/5 Xem code
2 KKKaneki Ken Python 1,000 ms - 3/5 Xem code

Học hỏi từ người khác

Giải pháp cộng đồng

Cảnh báo: Có 2 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem mã của người khác và đánh giá AI. Đăng nhập và giải thử thách để tham gia thảo luận.