Skip to content
Related Articles

Related Articles

Python program to print all Prime numbers in an Interval

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 27 Aug, 2022
Improve Article
Save Article

Given two positive integers start and end. The task is to write a Python program to print all Prime numbers in an Interval.

Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.

The idea to solve this problem is to iterate the val from start to end using a for loop and for every number, if it is greater than 1, check if it divides n. If we find any other number which divides, print that value.

Below is the Python implementation: 


# Python program to print all
# prime number in an interval
def prime(x, y):
    prime_list = []
    for i in range(x, y):
        if i == 0 or i == 1:
            for j in range(2, int(i/2)+1):
                if i % j == 0:
    return prime_list
# Driver program
starting_range = 2
ending_range = 7
lst = prime(starting_range, ending_range)
if len(lst) == 0:
    print("There are no prime numbers in this range")
    print("The prime numbers in this range are: ", lst)


The prime numbers in this range are: [2,3,5]

Time Complexity: O(N2), where N is the size of the range.

Auxiliary Space: O(N), since N extra space has been taken.

The above solution can be optimized using the Sieve of Eratosthenes. Please see print prime numbers in a range for details. 

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!