Open In App

Python Program to Print all Prime numbers in an Interval

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of printing all prime numbers in an interval in Python involves taking two input values representing a range [x, y] and finding all prime numbers within that range. A prime number is a natural number greater than 1 that is divisible only by 1 and itself. For example, in the interval [2, 7], the prime numbers are [2, 3, 5, 7].

Using sieve of eratosthenes

Sieve of Eratosthenes is one of the most efficient algorithms to find all prime numbers in a given range, especially for large intervals. It works by creating a boolean array where each index represents a number, and values are marked as True for prime and False for non-prime. The algorithm eliminates multiples of each prime starting from 2.

Python
x, y = 2, 7  # define the range [x, y]

# create a boolean list to mark primes, assume all are prime initially
primes = [True] * (y + 1)

# 0 and 1 are not prime
primes[0], primes[1] = False, False

# Sieve of Eratosthenes to mark non-primes
for i in range(2, int(y ** 0.5) + 1):
    if primes[i]:
        for j in range(i * i, y + 1, i):
            primes[j] = False

# collect primes in the range [x, y]
res = [i for i in range(x, y + 1) if primes[i]]
print(res if res else "No")

Output
[2, 3, 5, 7]

Explanation: It creates a boolean list assuming all numbers are prime. Starting from 2 to √y, it marks multiples of each prime as False i.e., non-prime. After this, indices marked as True represent prime numbers in the range.

Using trial division

Trial Division Method involves checking each number in the interval individually for primality. For each number, we test divisibility from 2 to √n. If a number is divisible by any value in this range, it is not prime. This method is simple and more efficient than the naive approach, especially for small intervals.

Python
x, y = 2, 7  # define range [x, y]

res = []  # list to store primes

for n in range(x, y + 1):
    if n <= 1:
        continue  # skip non-primes <= 1

    is_prime = True  # assume n is prime
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            is_prime = False  # n is not prime
            break

    if is_prime:
        res.append(n)  # add prime number

print(res if res else "No")

Output
[2, 3, 5, 7]

Explanation: For each number n in the range, it checks if n is greater than 1. It then assumes n is prime and checks divisibility from 2 to √n. If n is divisible by any number in this range, it is marked as non-prime. If no divisors are found, n is added to the result list.

Using sympy library

SymPy Library provides a built-in function called primerange(x, y) to generate prime numbers in a given range efficiently. It is the most convenient and requires minimal coding effort. Internally, SymPy uses optimized algorithms, including the sieve method. This is ideal when you need a quick and accurate solution without implementing the logic manually.

Python
from sympy import primerange 

x, y = 2, 7  # range [x, y]

primes = list(primerange(x, y + 1))
print(primes if primes else "No")

Output

[2, 3, 5, 7]

Explanation: sympy module, which generates prime numbers in a given range. The range is defined as [x, y] and primerange(x, y + 1) returns an iterator of prime numbers from x to y. The result is converted into a list and stored in primes.

Using naive approach

Naive Approach checks for primality by dividing each number from 2 to n//2. If any divisor is found, the number is not prime. This method is the least efficient and suitable only for small intervals . It is primarily used for understanding the basic concept of prime number checking.

Python
x, y = 2, 7  # range [x, y]
res = []  # list to store primes

for i in range(x, y + 1):
    if i <= 1:
        continue  # skip non-primes <= 1
    for j in range(2, i // 2 + 1):
        if i % j == 0:
            break  # not a prime
    else:
        res.append(i)  # prime found

print(res if res else "No")

Output
[2, 3, 5, 7]

Explanation: It loops through each number i from x to y and checks if i is a prime. If i is less than or equal to 1, it is skipped because primes are greater than 1. For each number i, it divides i by all numbers from 2 to i // 2. If any divisor is found, the loop breaks, indicating i is not prime. If no divisor is found, the else block runs, appending i to the result list.



Next Article
Article Tags :
Practice Tags :

Similar Reads