中級 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 つずつ開いてみましょう。

ヒント 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レビューも見ることができます。 サインインして課題を解くと議論に参加できます。