Prime numbers play a fundamental role in mathematics and computer science. They are widely used in cryptography, number theory, and data security. In this guide, we will explore how to write a Python program to print prime numbers within a given range.
By the end of this article, you will:
A prime number is a natural number greater than 1 that has only two factors: 1 and itself.
Suggested Visual: An infographic showing the first 10 prime numbers.
We iterate through all numbers in the given range and check if each number is prime.
pythonCopyEditdef is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1): # Optimization using square root
if n % i == 0:
return False
return True
def print_prime_numbers(start, end):
"""Print prime numbers in the given range."""
for num in range(start, end + 1):
if is_prime(num):
print(num, end=" ")
# Example: Find prime numbers between 10 and 50
start_range = 10
end_range = 50
print_prime_numbers(start_range, end_range)
CopyEdit11 13 17 19 23 29 31 37 41 43 47
Suggested Visual: A diagram showing how the square root optimization reduces iterations.
If you need to find prime numbers in a large range, the Sieve of Eratosthenes is a faster approach.
pythonCopyEditdef sieve_of_eratosthenes(n):
"""Find all prime numbers up to n using the Sieve of Eratosthenes."""
primes = [True] * (n + 1)
p = 2
while p * p <= n:
if primes[p]:
for i in range(p * p, n + 1, p):
primes[i] = False
p += 1
for p in range(2, n + 1):
if primes[p]:
print(p, end=" ")
# Example: Find prime numbers up to 50
sieve_of_eratosthenes(50)
Suggested Visual: A step-by-step breakdown of the Sieve of Eratosthenes algorithm.
Suggested Visual: An illustration of RSA encryption using prime numbers.
Prime numbers are an essential concept in programming and mathematics. Python makes it easy to generate prime numbers efficiently, whether using a basic loop or the Sieve of Eratosthenes for larger ranges.