 Open in App
Not now

# Python program to print all Prime numbers in an Interval

• Difficulty Level : Easy
• Last Updated : 07 Jan, 2023

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:

## Python3

 `# 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``:``            ``continue``        ``else``:``            ``for` `j ``in` `range``(``2``, ``int``(i``/``2``)``+``1``):``                ``if` `i ``%` `j ``=``=` `0``:``                    ``break``            ``else``:``                ``prime_list.append(i)``    ``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"``)``else``:``    ``print``(``"The prime numbers in this range are: "``, lst)`

Output:

`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.

Approach 2 : Sieve of Eratosthenes

## Python3

 `def` `sieve(x, y):``    ``# create a list of all the numbers in the range``    ``numbers ``=` `[i ``for` `i ``in` `range``(x, y``+``1``)]``    ` `    ``# start with the first number in the list``    ``i ``=` `0``    ` `    ``# loop until we reach the end of the list``    ``while` `i < ``len``(numbers):``        ``# if the current number is not already crossed out,``        ``# cross out all of its multiples``        ``if` `numbers[i] ``is` `not` `None``:``            ``for` `j ``in` `range``(i``+``numbers[i], ``len``(numbers), numbers[i]):``                ``numbers[j] ``=` `None``        ``i ``+``=` `1``    ` `    ``# return the list of prime numbers``    ``return` `[n ``for` `n ``in` `numbers ``if` `n ``is` `not` `None``]` `# Driver program``starting_range ``=` `2``ending_range ``=` `7``lst ``=` `sieve(starting_range, ending_range)``if` `len``(lst) ``=``=` `0``:``    ``print``(``"There are no prime numbers in this range"``)``else``:``    ``print``(``"The prime numbers in this range are: "``, lst)`

Output :

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

Time Complexity : O(nlogn)

Auxiliary Space : O(n)

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