เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Prime number sequence

A prime number is a natural number that is divisible only by 1 or itself (e.g. 3, 7, 11 etc.). However, 1 is not a prime number.

Your task is, given a list of candidate numbers cands, to filter only prime numbers in a new list primes.

But first, you need to create a function is_prime() that returns True if the input number \(n\) is prime or False, otherwise. To do so, it's sufficient to test if a number is not divisible by any integer number from 2 to \(\sqrt{n}\).

Tip: you might need to use the % operator that calculates a remainder from a division (e.g. 8 % 3 is 2).

The math module is already imported.

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Practicing Coding Interview Questions in Python

ดูคอร์ส

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

def is_prime(n):    
    # Define the initial check
    if n < ____:
       return ____
    # Define the loop checking if a number is not prime
    for i in range(____, ____):
        if ____:
            return False
    return True
แก้ไขและรันโค้ด