How to Check if a Number is Prime in Python: A Step-by-Step Guide 🐍


Check if a Number is Prime in Python

Prime numbers are an essential concept in mathematics and programming. A prime number is a natural number greater than 1 that is divisible only by 1 and itself. In this blog, we’ll explore how to check if a given number is prime using Python.

By the end of this post, you’ll understand how to:

  • Write a Python program to check if a number is prime.
  • Apply loops and conditionals to solve problems.
  • Optimize the program for better performance.

What is a Prime Number?

A prime number is a number greater than 1 that has no divisors other than 1 and itself. For example:

  • 2, 3, 5, 7, 11, 13, etc., are prime numbers.
  • Numbers like 4, 6, 8, and 9 are not prime because they have divisors other than 1 and themselves.

Steps to Check if a Number is Prime

To determine if a number is prime:

  1. If the number is less than or equal to 1, it’s not prime.
  2. If the number is greater than 1, check if it’s divisible by any number between 2 and the square root of the number. If it is divisible, the number is not prime.
  3. If no divisors are found, the number is prime.

How to Implement This in Python

Let’s write a Python program to check if a number is prime.

Basic Python Program to Check Prime Number

# Program to check if a number is prime

# Step 1: Take user input
num = int(input("Enter a number: "))

# Step 2: Define a function to check for prime
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

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

Explanation of the Code

  1. Taking User Input:
  • We use int(input()) to get the number from the user. The input is converted to an integer.
  1. Prime Check Function:
  • We define the function is_prime(n), which checks whether the number is prime.
  • If the number is less than or equal to 1, it’s not prime.
  • We loop through numbers from 2 to n-1 to check if n is divisible by any of these numbers. If it is, the number is not prime.
  1. Output:
  • The program checks the result of the is_prime() function and prints whether the number is prime or not.

Sample Output

Here’s what the program looks like when it’s run:

Enter a number: 17
17 is a prime number.

In this example, the user entered 17, which is a prime number, so the program confirms it.

Optimizing the Prime Check

The basic program works but can be made more efficient. Instead of checking all numbers up to n-1, we can optimize it by checking divisors only up to the square root of the number, because a larger factor of the number would be paired with a smaller factor that we’ve already checked.

Here’s an optimized version:

Optimized Python Program

import math

# Program to check if a number is prime (optimized)

# Step 1: Take user input
num = int(input("Enter a number: "))

# Step 2: Define an optimized function to check for prime
def is_prime_optimized(n):
    if n <= 1:
        return False
    if n == 2:
        return True  # 2 is the only even prime number
    if n % 2 == 0:
        return False  # Any other even number is not prime
    for i in range(3, int(math.sqrt(n)) + 1, 2):  # Check odd numbers up to sqrt(n)
        if n % i == 0:
            return False
    return True

# Step 3: Call the function and display the result
if is_prime_optimized(num):
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Explanation of Optimized Code

  1. Square Root Optimization:
  • Instead of looping up to n-1, we loop only up to sqrt(n). This reduces the number of iterations, making the program more efficient.
  1. Even Number Check:
  • If the number is even (except for 2), we know it’s not prime, so we can return False immediately, skipping unnecessary checks.
  1. Loop Over Odd Numbers:
  • We skip even numbers entirely after checking if the number is divisible by 2. This saves time in larger numbers where unnecessary checks for even divisibility are redundant.

Sample Output of Optimized Program

Enter a number: 29
29 is a prime number.

When the user enters 29, the program efficiently checks and confirms that 29 is a prime number.

Real-Life Application of Prime Numbers

Prime numbers are not only important in mathematics but also have practical applications in computer science and cryptography. Many encryption algorithms, like RSA, rely on prime numbers to secure data. Understanding prime numbers and how to work with them is a valuable skill for anyone interested in coding, algorithms, or cybersecurity.

Conclusion

In this blog, you learned how to:

  • Implement a basic Python program to check if a number is prime.
  • Optimize the program to make it faster by reducing the number of checks.
  • Use loops, conditionals, and mathematical functions like sqrt() in Python.

Prime number checking is a great exercise for beginners to practice programming logic, and understanding how to optimize code is a crucial skill as you grow in your Python journey.

Feel free to share your results or any questions in the comments! And don’t forget to check out more Python tutorials on this page for more learning. 😊


Stay tuned for more beginner-friendly Python tutorials! Happy coding! 🐍

Share with our team

Leave a Comment