To check if a number is prime in Python, you need to verify if it has no divisors other than 1 and itself (excluding 1 and the number itself). Here's how you can write a Python program to check for prime numbers:
def is_prime(num): # Prime numbers are greater than 1
if num <= 1:
return False
# Check for factors from 2 to sqrt(num)
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
Explanation:
- The function
is_prime(num)
takes an integernum
as input and returnsTrue
ifnum
is a prime number, andFalse
otherwise.
- Edge case: Numbers less than or equal to 1 are not prime (
num <= 1
).
- Prime number definition: Prime numbers are greater than 1 and have no divisors other than 1 and itself.
- Efficient checking: The loop runs from 2 to the square root of
num
(int(num**0.5) + 1
). This is because, ifnum
is divisible by any number greater than its square root, the corresponding factor would necessarily be less than its square root.
- Divisibility check: For each number
i
in the range, ifnum
is divisible byi
(num % i == 0
), thennum
is not prime (return False
).
Example Usage:
You can test the is_prime
function with different numbers:
num1 = 17num2 = 24
num3 = 2
print(f"Is {num1} prime? {is_prime(num1)}") # Output: True
print(f"Is {num2} prime? {is_prime(num2)}") # Output: False
print(f"Is {num3} prime? {is_prime(num3)}") # Output: True
In the example above:
num1
(17) is a prime number.num2
(24) is not a prime number (divisible by 2, 3, 4, 6, 8, 12).num3
(2) is a prime number.
This function efficiently checks whether a given number is prime using a simple iterative approach with a time complexity of , which is efficient for most practical purposes.