Python Program To Print All Prime Numbers in an Interval

1. Introduction

Prime numbers are natural numbers greater than 1 that have no positive divisors other than 1 and themselves. Finding prime numbers within a specific interval is a common problem that helps in understanding the fundamentals of number theory and programming logic. This blog post will guide you through creating a Python program to print all prime numbers within a given interval.

2. Program Steps

1. Prompt the user to enter the start and end of the interval.

2. For each number in the interval, check if it is a prime number.

3. To check for a prime number, see if it has any divisor other than 1 and itself.

4. If a number is prime, print it.

3. Code Program

# Step 1: Get the interval start and end from the user
start = int(input("Enter the start of the interval: "))
end = int(input("Enter the end of the interval: "))

# Function to check if a number is prime
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

# Step 2 & 3: Iterate through the interval and print prime numbers
print(f"Prime numbers between {start} and {end} are:")
for num in range(start, end + 1):
    if is_prime(num):
        print(num, end=' ')

Output:

Enter the start of the interval: 10
Enter the end of the interval: 50
Prime numbers between 10 and 50 are:
11 13 17 19 23 29 31 37 41 43 47

Explanation:

1. The program begins by asking the user for the start and end points of the interval within which to find prime numbers. These are read from the standard input and converted into integers.

2. A helper function is_prime is defined to check if a given number n is prime. It first checks if n is less than or equal to 1, in which case it returns False as the number is not prime. Then, for each number from 2 up to the square root of n (inclusive), it checks if n is divisible by any of these numbers. If n is divisible by any number other than 1 and itself, it is not prime, and the function returns False. If no divisors are found, the function returns True, indicating that n is prime.

3. The program then iterates through each number in the specified interval. For each number, it calls the is_prime function. If the function returns True, indicating the number is prime, the program prints the number.

4. The output lists all prime numbers within the specified interval, demonstrating the program's ability to identify prime numbers efficiently.


Comments