Determining whether a number is prime is a fundamental problem in programming and mathematics. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this blog, we’ll explore how to check if a number is prime using Python, a versatile and beginner-friendly programming language.
We’ll start by explaining the basic logic behind prime numbers and then walk you through a simple Python program to check for primality. You’ll learn how to implement a brute-force approach, which checks divisibility for all numbers up to the square root of the given number, and understand why this method is efficient. Additionally, we’ll discuss optimizations to make the algorithm faster, such as skipping even numbers after checking for divisibility by 2.
Whether you’re a beginner or an experienced programmer, this guide will help you grasp the concept of prime numbers and how to implement them in Python. By the end, you’ll have a clear understanding of the logic and code required to determine if a number is prime, along with practical examples to test your knowledge. Let’s dive into the world of prime numbers and Python programming!
Problem Statement:
Write a Python function to check if a given number is prime.
Solution Explanation:
- A prime number is a number greater than 1 that has only two factors: 1 and itself.
- We check divisibility from 2 to the square root of the number for efficiency.
Python Code:
def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True # Test cases print(is_prime(2)) # Output: True print(is_prime(11)) # Output: True print(is_prime(15)) # Output: False print(is_prime(29)) # Output: True
Example Output:
Input: 2 → Output: True
Input: 11 → Output: True
Input: 15 → Output: False
Input: 29 → Output: True