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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)