Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to print all Prime numbers in an Interval
In this article, we will learn how to find and print all prime numbers within a given range using Python. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Problem statement ? We are given an interval and need to compute all the prime numbers in the given range.
We'll use a brute-force approach based on the basic definition of prime numbers. For each number in the range, we check if it has any divisors between 2 and itself (excluding 1 and the number itself).
Basic Approach
The algorithm checks each number in the range by testing divisibility from 2 up to the number minus 1. If no divisors are found, the number is prime ?
start = 1
end = 37
for val in range(start, end + 1):
# If num is divisible by any number
# between 2 and val, it is not prime
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
else:
print(val)
2 3 5 7 11 13 17 19 23 29 31 37
Optimized Approach
We can optimize by checking divisors only up to the square root of the number, since factors come in pairs ?
import math
start = 10
end = 50
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
print(f"Prime numbers between {start} and {end}:")
for num in range(start, end + 1):
if is_prime(num):
print(num)
Prime numbers between 10 and 50: 11 13 17 19 23 29 31 37 41 43 47
How It Works
Using a Function for Reusability
Creating a reusable function makes the code cleaner and more modular ?
def find_primes_in_range(start, end):
"""Find all prime numbers in the given range"""
primes = []
for num in range(max(2, start), end + 1):
is_prime = True
for divisor in range(2, int(num ** 0.5) + 1):
if num % divisor == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return primes
# Example usage
start_range = 20
end_range = 40
prime_numbers = find_primes_in_range(start_range, end_range)
print(f"Prime numbers between {start_range} and {end_range}:")
print(prime_numbers)
Prime numbers between 20 and 40: [23, 29, 31, 37]
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Basic Check | O(n²) | O(1) | Small ranges |
| Square Root Optimization | O(n?n) | O(1) | Medium ranges |
| Sieve of Eratosthenes | O(n log log n) | O(n) | Large ranges |
Conclusion
The basic approach checks all possible divisors, while the optimized version only checks up to the square root. For larger ranges, consider using the Sieve of Eratosthenes algorithm for better performance.
