Write a function is_prime(n) that returns True when n is prime. Read n and print YES if it is prime, otherwise NO. (1 is not prime.)
What to build
A function that returns True or False.
Requirements
- Write
is_prime(n), returningTruefor a prime. - Remember that 1 is not prime.
- Print
YESorNO.
Input
One whole number n from 1 to 1000000.
Output
YES or NO.
Constraints
n is from 1 to 1000000.
Example
Input:
7
Output:
YES
Why it works
A number with a divisor larger than its square root must also have a smaller one, so the search can stop at the square root.
Examples
Example 1 · Input
7
Expected output
YES
Example 2 · Input
1
Expected output
NO
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Checking divisors d while d * d <= n is enough.
Hint 2
A prime has no divisor between 2 and n - 1.
Solution
Show one correct solution (try it yourself first)
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")