Introduction
Printing all prime numbers within a specific interval is a common task in programming. This tutorial will guide you through creating a Python program that finds and prints all prime numbers within a given range.
Problem Statement
Create a Python program that:
- Takes two numbers as input, representing the lower and upper bounds of an interval.
- Finds and prints all prime numbers within this interval.
Example:
- Input:
start = 10
,end = 50
- Output:
Prime numbers between 10 and 50 are: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
Solution Steps
- Take Input for the Interval: Use the
input()
function to get the lower and upper bounds from the user. - Convert Input to Integers: Convert the input strings to integers using
int()
. - Check Each Number in the Interval: For each number in the range, check if it is prime.
- Display the Prime Numbers: Collect and display all prime numbers found within the interval.
Python Program
# Python Program to Print All Prime Numbers in an Interval # Author: https://www.rameshfadatare.com/ import math # Step 1: Take input for the interval start = int(input("Enter the start of the interval: ")) end = int(input("Enter the end of the interval: ")) # Step 2: Check each number in the interval print(f"Prime numbers between {start} and {end} are:") for num in range(start, end + 1): if num > 1: # Prime numbers are greater than 1 is_prime = True for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: is_prime = False break if is_prime: print(num, end=" ") print() # For a newline after printing all prime numbers
Explanation
Step 1: Take Input for the Interval
- The
input()
function prompts the user to enter the start and end of the interval. The inputs are converted to integers usingint()
.
Step 2: Check Each Number in the Interval
- The program iterates over each number in the specified range. For each number greater than 1, it checks if the number is divisible by any number from 2 to the square root of that number. If no divisors are found, the number is prime.
Step 3: Display the Prime Numbers
- The
print()
function is used to display all prime numbers found within the interval. The numbers are printed on the same line, separated by spaces.
Output Example
Example:
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
Example:
Enter the start of the interval: 5 Enter the end of the interval: 20 Prime numbers between 5 and 20 are: 5 7 11 13 17 19
Conclusion
This Python program demonstrates how to find and print all prime numbers within a specified interval. It effectively combines loops, conditionals, and mathematical concepts, making it a valuable example for beginners learning about prime numbers and control structures in Python.