Advertisement
When writing programs that involve numbers, it's common to run into problems where you need to figure out if a number is prime or not. Prime numbers are simple in concept but useful in many situations, from basic exercises to more advanced programming tasks. In Python, writing a program that deals with prime numbers is a good way to work on loops, conditions, and performance. Let’s go through how to create different versions of a prime number program, each with a slightly different focus.
A prime number is any integer larger than 1 that can only be divided by one and itself. So, that means when you try to divide it by anything except for those two numbers, you get a remainder. So 2, 3, 5, and 7 are prime numbers. Numbers such as 4, 6, or 9 aren't because they can be divided by other numbers without a remainder.
This idea is pretty straightforward, but it’s a useful concept in both math and programming. In coding, prime numbers show up in problem-solving, puzzles, and even in some background parts of security and encryption systems.
To begin, create a simple function that checks whether a number is prime. This version checks all numbers between 2 and one less than the input:
python
CopyEdit
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
Here's what happens: The loop runs through all numbers starting at two and going up to, but not including, n. If any number divides n without a remainder, the function immediately returns False, meaning n isn't prime. If the loop finishes without finding a match, the number is declared prime.
The basic version works fine for smaller inputs, but it does more work than needed. If a number has a factor, that factor will always be less than or equal to its square root. So, there’s no need to go all the way up to n-1. You can stop at the square root, which reduces the number of checks:
python
CopyEdit
import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
This saves time and makes the function more practical when you're checking higher numbers. The result is the same, but the loop doesn’t run as long.
Once your is_prime function is ready, it becomes easy to apply it to a set of numbers. You can write a second function that goes through a given range and prints the prime numbers one by one:
python
CopyEdit
def primes_in_range(start, end):
for num in range(start, end + 1):
if is_prime(num):
print(num)
So if you call:
python
CopyEdit
primes_in_range(10, 30)
It will print the prime numbers between 10 and 30. This is useful when you’re exploring a dataset or writing a utility that scans numeric ranges.
If you want to generate prime numbers up to a certain limit and do it quickly, especially when that limit is high, you can use the Sieve of Eratosthenes. It works by assuming all numbers are prime and then crossing off the ones that aren’t.
Here's what it looks like in Python:
python
CopyEdit
def sieve_of_eratosthenes(limit):
primes = [True] * (limit + 1)
primes[0] = primes[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if primes[i]:
for j in range(i * i, limit + 1, i):
primes[j] = False
for i in range(limit + 1):
if primes[i]:
print(i)
When you run:
python
CopyEdit
sieve_of_eratosthenes(100)
It prints every prime from 0 to 100. This method is a smart choice when performance matters, especially if you're dealing with repeated calls or need to work with large numeric data.
There are times when printing isn’t enough—you may want to keep the primes in a list and use them later in your code. This is where list comprehension helps:
python
CopyEdit
primes = [x for x in range(2, 101) if is_prime(x)]
print(primes)
This one-liner checks each number from 2 to 100 and keeps the ones that pass the is_prime test. It’s useful when you need to filter or analyze primes later instead of just displaying them.
Once you're comfortable writing the basic prime checker and using it in different ways, there are other variations worth exploring:
Instead of printing, count and return the total number of primes:
python
CopyEdit
def count_primes(start, end):
count = 0
for num in range(start, end + 1):
if is_prime(num):
count += 1
return count
This can be helpful in scripts where the output needs to be processed further:
python
CopyEdit
def list_primes(start, end):
return [num for num in range(start, end + 1) if is_prime(num)]
Sometimes, you might have a predefined list and want to test each item:
python
CopyEdit
def check_multiple(numbers):
return {n: is_prime(n) for n in numbers}
These variations are optional, but once you know how the core logic works, it's simple to build around it.
A prime number program in Python isn't just a beginner's exercise. It gives you a clear way to understand how loops, logic checks, and number handling work. You start with a basic version that checks one number, then expand to working with ranges, and then improve your logic for speed. As you write each version, you're building code that does more with less effort.
And while built-in libraries can do the heavy lifting for more advanced use cases, learning to write it yourself first is a solid step. It helps you reason through each part of your code and see where you can write smarter, cleaner logic. Try each version out, compare how they perform, and use what fits best for your current project.
Advertisement
Understand how the Python range() function works, how to use its start, stop, and step values, and why the range object is efficient in loops and iterations
Explore the XOR Problem with Neural Networks in this clear beginner’s guide. Learn why simple models fail and how a multi-layer perceptron solves it effectively
Meta's scalable infrastructure, custom AI chips, and global networks drive innovation in AI and immersive metaverse experiences
Need to convert a Python list to a NumPy array? This guide breaks down six reliable methods, including np.array(), np.fromiter(), and reshape for structured data
Still unsure about Git push and pull? Learn how these two commands help you sync code with others and avoid common mistakes in collaborative projects
Learn the top 7 impacts of the DOJ data rule on enterprises in 2025, including compliance, data privacy, and legal exposure.
Discover how to generate enchanting Ghibli-style images using ChatGPT and AI tools, regardless of your artistic abilities
What happens when you stop relying on majority vote and start using smarter label aggregation? See how Distilabel and Argilla helped build a chatbot with clearer, more consistent labels and faster feedback cycles
NPC-Playground is a 3D experience that lets you engage with LLM-powered NPCs in real-time conversations. See how interactive AI characters are changing virtual worlds
Explore key features, top benefits, and real-world use cases of OpenAI reasoning models that are transforming AI in 2025.
Learn how to write a prime number program in Python. This guide walks through basic checks, optimized logic, the Sieve of Eratosthenes, and practical code examples
How Python handles names with precision using namespaces. This guide breaks down what namespaces in Python are, how they work, and how they relate to scope