Python Program to Check if a Number is Prime

1. Introduction

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Determining whether a number is prime is a classic problem in mathematics and computer science, serving as a fundamental task in cryptography, number theory, and algorithmic challenges. This blog post will explore how to check if a number is prime using Python, highlighting a method that balances simplicity and efficiency.

2. Program Steps

1. Prompt the user to enter a number.

2. Check if the number is less than 2, in which case it is not prime.

3. For numbers 2 and above, check for factors from 2 to the square root of the number. If any divisor is found, the number is not prime.

4. If no divisors are found, the number is prime.

5. Display the result to the user.

3. Code Program

# Step 1: Prompt the user for a number
num = int(input("Enter a number: "))

# Function to check if a number is prime
def is_prime(n):
    # Step 2: Numbers less than 2 are not prime
    if n < 2:
        return False
    # Step 3: Check for factors from 2 up to the square root of n
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

# Step 4: Determine if the number is prime and display the result
if is_prime(num):
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Output:

Enter a number: 11
11 is a prime number.

Explanation:

1. The user is prompted to input a number, which is read as an integer and stored in the variable num.

2. The program defines a function is_prime that checks if the given number n is prime. It first verifies if n is less than 2, in which case it immediately returns False because numbers less than 2 are not prime by definition.

3. For numbers 2 and above, the function checks for divisors by iterating from 2 up to the square root of n (inclusive). This range is sufficient because if n has a factor larger than its square root, then it must also have a factor smaller than the square root, and the function would have found it by this point.

4. If the function finds a divisor in this range, it returns False, indicating that n is not prime. If no divisors are found, the function returns True, indicating that n is prime.

5. Based on the return value of is_prime, the program prints out whether the entered number is prime or not, providing a straightforward way to determine the primality of a number in Python.


Comments