समस्या
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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।