Python Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes
This is a Python Program to print prime numbers in a range using Sieve of Eratosthenes.
Problem Description
The program takes a range and prints prime numbers in that range using Sieve of Eratosthenes.
Problem Solution
1. Take the value of n from the user.
2. Initialise the sieve with numbers from 2 to n.
3. Use a while loop with the condition that the sieve is not empty
4. Get the smallest number that is prime
5. Remove that number and it’s multiples
6. Continue till the sieve is empty
7. Exit
Program/Source Code
Here is the source code of the Python Program to takes a range and print prime numbers in that range using Sieve of Eratosthenes. The program output is also shown below.
n=int(input("Enter upper limit of range: "))
sieve=set(range(2,n+1))
while sieve:
prime=min(sieve)
print(prime,end="\t")
sieve-=set(range(prime,n+1,prime))
print()
Runtime Test Cases
Case 1:
Enter upper limit of range: 10
2 3 5 7
Case 2:
Enter upper limit of range: 15
2 3 5 7 11 13