簡単 7件解決済み 正答率38.9%

Prime Number Check

Decide whether a number is prime.

このチャレンジで学べること

  • Test divisibility with the % operator
  • Stop checking at the square root of n
  • Handle 0, 1 and 2 as special cases

問題

翻訳を表示

A prime number is greater than 1 and divisible only by 1 and itself. Checking divisors up to the square root of n is enough.

Implement is_prime(n).

Input

n: The number to test.

Output

Return true if n is prime, otherwise false.

制約

-1,000 ≤ n ≤ 1,000,000,000,000

例

例 1
入力:
n = 29

期待される出力:
expected = True
入力:
long long n = 29;

期待される出力:
bool expected = true;
入力:
long n = 29;

期待される出力:
bool expected = true;

解説

29 has no divisors other than 1 and 29.

例 2
入力:
n = 21

期待される出力:
expected = False
入力:
long long n = 21;

期待される出力:
bool expected = false;
入力:
long n = 21;

期待される出力:
bool expected = false;

解説

21 = 3 × 7, so it is not prime.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Handle numbers below 2 first; they cannot be prime.

ヒント 2

Test possible divisors only up to the square root of the number.

ヒント 3

Watch out for even numbers and repeated factors, since one divisor is enough to disqualify primality.

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 ННикита Python 1,059 ms - 5/5 コードを見る
2 AAmir Python 1,098 ms - - コードを見る
3 KKKaneki Ken Python 1,137 ms - 5/5 コードを見る
4 JPJittipat Phonhan Go 1,547 ms - 5/5 コードを見る
5 GTGarlic The Destroyer Rust 1,759 ms - 2/5 コードを見る
6 HJhettory Jurash C++ 4,287 ms - 4/5 コードを見る
7 PTphúc thịnh phạm C++ 4,447 ms - 4/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意:下に7件の全解答あり まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。