• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Prime Numbers within a Given Range using Sieve of Eratosthenes

  • July 14, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial -:
  • Understanding the Problem
  • Developing the Algorithm
  • Writing the Python Code
  • Time Complexity
  • Code Explanation
  • Dry Run
Prime Numbers within a Given Range using Sieve of Eratosthenes
Prime Numbers within a Given Range using Sieve of Eratosthenes

Understanding the Problem

Before diving into the code, it’s essential to have a clear understanding of what prime numbers are and the problem at hand. Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. Our goal is to write a program that can identify all the prime numbers within a given range specified by the user.



Developing the Algorithm

To find prime numbers within a given range, we can use a simple algorithm known as the “Sieve of Eratosthenes.” This algorithm works by iteratively eliminating multiples of each prime number found, gradually narrowing down the list of potential primes.

The steps involved in the algorithm are as follows:

  1. Create a list of numbers from the starting point to the ending point of the range.
  2. Start with the first number in the list and mark it as a prime number.
  3. Eliminate all multiples of the current prime number from the list.
  4. Move to the next unmarked number and repeat step 3 until all numbers have been processed.
  5. The remaining unmarked numbers in the list are prime numbers within the given range.

Writing the Python Code

Now, let’s implement the algorithm in Python. Below is the code snippet that accomplishes this task:

# Python program to print prime numbers within a given range

def print_prime_numbers(start, end):
    primes = []
    prime_flags = [True] * (end + 1)
    p = 2

    while p * p <= end:
        if prime_flags[p] is True:
            for i in range(p * p, end + 1, p):
                prime_flags[i] = False
        p += 1

    for p in range(start, end + 1):
        if prime_flags[p]:
            primes.append(p)

    return primes

start_range = int(input("Enter the starting range: "))
end_range = int(input("Enter the ending range: "))

prime_numbers = print_prime_numbers(start_range, end_range)

print("Prime numbers within the given range are:")
for prime in prime_numbers:
    print(prime, end=" ")

O/P

Enter the starting range: 1
Enter the ending range: 100
Prime numbers within the given range are:

1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Time Complexity

The time complexity of the code for finding prime numbers within a given range using the Sieve of Eratosthenes algorithm is O(n log log n), where n represents the ending range of the input.

Code Explanation

Let’s go through the code to understand how it works:

1. The print_prime_numbers function takes the starting and ending range as input parameters.

2. A list called primes is initialized to store the prime numbers found within the range.

3. A Boolean list, prime_flags, is created with True values for each number in the range.

4. The algorithm starts with the first prime number, 2, and iterates until the square root of the ending range.

5. Within the loop, it checks if a number is marked as prime. If it is, it eliminates its multiples by updating the prime_flags list accordingly.

6.After the loop completes, the function iterates through the range again and appends the remaining prime numbers to the primes list.

7. The function returns the list of prime numbers.

8. User input is taken for the starting and ending range.

9. The print_prime_numbers function is called, and the resulting prime numbers are stored in prime_numbers.

10. Finally, the prime numbers are printed to the console.



Dry Run

To ensure a clear understanding, let’s perform a dry run of the code with an example:

1. Suppose the user enters a starting range of 10 and an ending range of 30.

2. The function is called with start_range = 10 and end_range = 30.

3. The algorithm begins, initializing primes as an empty list and prime_flags as a list of True values up to 30.

4. Starting with the first prime number, 2, it eliminates its multiples from the prime_flags list: 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30.

5. The loop moves to the next unmarked number, 3, and eliminates its multiples: 9, 15, 21, 27.

6. The loop proceeds to the next unmarked number, 5, and eliminates its multiples: 25.

7. The remaining numbers in the prime_flags list that are marked as True (prime) are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].

8. The function returns this list of prime numbers.

9. The prime numbers within the given range are printed to the console: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.





Tags: Efficient prime number finder in Python using Sieve of EratosthenesFinding prime numbers in a range with Sieve of Eratosthenes PythonHow to find prime numbers within a range using Sieve of EratosthenesPrime number calculation in Python using Sieve of EratosthenesPrime number determination within a range with Sieve of Eratosthenes in PythonPrime number generator Python code using Sieve of EratosthenesPrime numbers within a given range Sieve of Eratosthenes PythonPython algorithm to generate prime numbers within a given rangePython code for efficient prime number identification in a rangePython function to check prime numbers using Sieve of EratosthenesPython program for prime numbers within a range using Sieve of EratosthenesPython program to find prime numbers using Sieve of EratosthenesPython program to list prime numbers using Sieve of EratosthenesSieve of Eratosthenes algorithm for prime numbers in PythonSieve of Eratosthenes code in Python for finding prime numbersSieve of Eratosthenes implementation for prime numbers PythonSieve of Eratosthenes implementation in Python for prime numbersSieve of Eratosthenes Python implementation for prime numbersStep-by-step guide to finding prime numbers with Sieve of Eratosthenes in PythonTutorial: Sieve of Eratosthenes for prime numbers in Python
  • Previous Fetching data from Dynamodb using get_item function with Python Boto3
  • Next Finding Prime Numbers within a Given Range in Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.