Python Program to Check if a Number is Prime
This program checks whether a given number is prime.
Python Code:
def is_prime(number):
"""
Function to check if a given number is prime.
Parameters:
number (int): The number to be checked.
Returns:
bool: True if the number is prime, False otherwise.
"""
if number <= 1:
return False # 1 and numbers less than 1 are not prime
if number == 2:
return True # 2 is prime
if number % 2 == 0:
return False # Even numbers greater than 2 are not prime
# Check for factors from 3 up to the square root of the number
# We only need to check odd numbers
for i in range(3, int(number**0.5) + 1, 2):
if number % i == 0:
return False # If divisible, not a prime number
return True # If no factors found, the number is prime
# Example usage: number_to_check = 29 result = is_prime(number_to_check) print(f"{number_to_check} is prime: {result}") # Example usage: number_to_check = 29 result = is_prime(number_to_check) print(f"{number_to_check} is prime: {result}")
Output:
Example: Check if 29
is prime. Result: True
Explanation:
The is_prime
function uses basic number theory to determine if a number is prime. It first checks for edge cases (numbers less than or equal to 1, even numbers excluding 2). Then, it iterates through potential factors up to the square root of the number, skipping even numbers after checking for divisibility by 2.
For the given example, 29
is a prime number, so the function correctly returns True
.