Python bootcamp · Lab 29

Prime check

mediumFunctions12 minLesson: Functions

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Write is_prime(n) that returns True if n is a prime number, else False.

main already reads n and prints yes or no. 1 is not prime. 2 is.

Input. One line: an integer n ≥ 1.

Output. yes or no.

Constraints

  • 1 ≤ n ≤ 10,000

Examples

Example 1
Input
7
Output
yes
Example 2 — 1 is not prime.
Input
1
Output
no
Example 3
Input
9
Output
no
Hint
  1. Return False immediately for n < 2.
  2. Trial-divide from 2 through int(n**0.5). If any divisor hits, it is composite.
Show correct code

Peek only after you have tried. You can still Check your own version.

def is_prime(n):
    if n < 2:
        return False
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d += 1
    return True

n = int(input())
print("yes" if is_prime(n) else "no")
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.