ง่าย 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

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 ได้ เข้าสู่ระบบและแก้โจทย์เพื่อร่วมพูดคุย