Python program to check prime number
Description: Write a Python program to check whether a number is prime.
Rules and hints:
- A prime number is greater than 1 and has no divisor other than 1 and itself.
- You only need to test divisors up to the square root of the number.
Python program to check a prime number
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
for n in (2, 15, 17, 1):
if is_prime(n):
print(n, "is prime")
else:
print(n, "is not prime")
Output:
Tutorials Class - Output Window
2 is prime
15 is not prime
17 is prime
1 is not prime
How it works
- Numbers below 2 are not prime.
- For 15 the loop tests 2 and 3. Since
15 % 3 == 0, it returnsFalse. - For 17 the loop tests 2, 3 and 4. None divides it, so it is prime.
- As soon as one divisor is found,
return Falseends the function early.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |