Menu Close

Find all prime numbers in a range using Sieve of Eratosthenes

Python Program to Read & Print Prime Numbers in a Range using Sieve of Eratosthenes.

To find all the prime numbers less than or equal to a given integer n by Eratosthenes’ method:

Create a list of consecutive integers from 2 through n: (2, 3, 4, …, n).

Initially, let p equal 2, the smallest prime number.

Enumerate the multiples of p by counting to n from 2p in increments of p, and mark them in the list (these will be 2p, 3p, 4p, …; the p itself should not be marked).

Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.

When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n.

n=int(input("Integer_N: "))
print("\nPrime Numbers:")
sieve=set(range(2,n+1))
while sieve:
    prime=min(sieve)
    print(prime,end="\n")
    sieve-=set(range(prime,n+1,prime))
print()

INPUT_1:
Integer_N:  5

OUTPUT:
Prime Numbers:
2
3
5


INPUT_2:
Integer_N:  20

OUTPUT:
Prime Numbers:
2
3
5
7
11
13
17
19


ILLUSTRATION

Executed using python3 terminal Linux

Morae Q!

  1. Program to get dictionary items, use update module and items module.
  2. Regular expression allowing certain set of characters.
  3. Compute the Sum of Cosine Series.
  4. Find the Sum of Sine Series.
  5. Remove the Vowels from the string.
  6. Find All Non-Overlapping strings/characters using regular expressions .
  7. Check whether the given string is Panagram or not.
  8. Replacing strings using Regular Expression Regex.
  9. Check whether the given number is Strong number or not.
  10. Find the numbers divisible by a input numbers within the given range.
  11. Change the behaviour of the Regular Expression using flags.
  12. Find the exponentiation of a number.
  13. Find all prime numbers in a range using Sieve of Eratosthenes.
  14. Convert decimal equivalent into binary, hexadecimal and octal.
  15. Compute the area of a farmers field in feet.
  16. Compute time from number of days/hours to seconds.
  17. Precompiled patterns using Regular Expressions .
  18. Compute the price of the cake on the nth day.
  19. Compute the number of possible non-increasing arrays.
  20. Find the type of spinach using the calorie value.