ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก