簡単 0件解決済み 正答率0%

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用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。