Python Program to Display Prime Numbers between Given Interval

Prime number

Python program to display prime numbers between given interval has been shown here. For example, the prime numbers between 10 and 20 are 11, 13, 17, 19. In this program, the upper and lower bounds of the interval are taken as inputs.







1. Algorithm to Display Prime Numbers between Given Interval


1. Take lower bound l and upper bound u as inputs.

2. For each number from l to u, check if it is a prime number.

3. If a number is prime, add it to a list of prime numbers.

4. Display the list after all the numbers within the interval have been checked.




2. Pseudocode to Display Prime Numbers between Given Interval


Input : Lower bound $l$ and Upper bound $u$

Output : Prime numbers between $l$ and $u$

1. Procedure primesBetweenInterval($l, u$):

2. Repeat for $n \in [l, u]$:

3. $flag \leftarrow 0$

4. Repeat for $i \in [2, \sqrt{n}]$:

5. If $n \mod i$ = 0:

6. $flag \leftarrow 1$

7. break

8. If $flag = 0$:

9. Print "$n$ is a prime"

10. End Procedure





3. Time complexity to Display Prime Numbers between Given Interval


Time Complexity: O($n\sqrt{n}$)

Here, $n$ is the number of elements between $l$ and $u$ inclusive




4. Python Program & output to Display Prime Numbers between Given Interval

Code has been copied
# *********************************
#    	alphabetacoder.com
#  Python program to display prime
#  numbers between given intervals
# *********************************

# function to check prime
def check_prime(num):
    # no prime number less than 2, so return false
    if num < 2:
        return 0
    # check divisibility of num
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return 0
            # num is composite so return false

    # num is prime so return true
    return 1


def main():
    # take input of the inteval
    n1 = int(input("Enter the lower bounds of interval = "))
    n2 = int(input("Enter the upper bounds of interval = "))

    print("Prime numbers between", n1, "and", n2, ": ")
    # find primes between n1 and n2
    for i in range(n1, n2 + 1):
        # check if current number is prime
        if check_prime(i) == 1:
            print(i, end=" ")


# driver code
main()

Output


Enter the lower bounds of interval = 10

Enter the upper bounds of interval = 60

Prime numbers between 10 and 60 :

11 13 17 19 23 29 31 37 41 43 47 53 59