Prime number check
Class 11-12 · PythonWrite a Python program to check whether a number is prime.
is_prime(29) → True, and is_prime(15) → False (15 % 3 == 0)
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter a number: "))
print(is_prime(num))
- A number is prime if it has no divisors other than 1 and itself, so numbers n <= 1 are not prime.
- The loop checks divisors from 2 up to int(n ** 0.5) + 1. If n = a × b with a <= b, then a <= √n, so checking beyond the square root is unnecessary.
- If any i divides n exactly (n % i == 0), the function returns False at once.
- Dry run for n = 29: √29 ≈ 5.4, so i runs over 2, 3, 4, 5. None divides 29, so the function returns True.