Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to print all the numbers divisible by 3 and 5 for a given number
Next article icon

Python Program to Print all Prime numbers in an Interval

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of printing all prime numbers in an interval in Python involves taking two input values representing a range [x, y] and finding all prime numbers within that range. A prime number is a natural number greater than 1 that is divisible only by 1 and itself. For example, in the interval [2, 7], the prime numbers are [2, 3, 5, 7].

Using sieve of eratosthenes

Sieve of Eratosthenes is one of the most efficient algorithms to find all prime numbers in a given range, especially for large intervals. It works by creating a boolean array where each index represents a number, and values are marked as True for prime and False for non-prime. The algorithm eliminates multiples of each prime starting from 2.

Python
x, y = 2, 7  # define the range [x, y]  # create a boolean list to mark primes, assume all are prime initially primes = [True] * (y + 1)  # 0 and 1 are not prime primes[0], primes[1] = False, False  # Sieve of Eratosthenes to mark non-primes for i in range(2, int(y ** 0.5) + 1):     if primes[i]:         for j in range(i * i, y + 1, i):             primes[j] = False  # collect primes in the range [x, y] res = [i for i in range(x, y + 1) if primes[i]] print(res if res else "No") 

Output
[2, 3, 5, 7] 

Explanation: It creates a boolean list assuming all numbers are prime. Starting from 2 to √y, it marks multiples of each prime as False i.e., non-prime. After this, indices marked as True represent prime numbers in the range.

Table of Content

  • Using trial division
  • Using sympy library
  • Using naive approach

Using trial division

Trial Division Method involves checking each number in the interval individually for primality. For each number, we test divisibility from 2 to √n. If a number is divisible by any value in this range, it is not prime. This method is simple and more efficient than the naive approach, especially for small intervals.

Python
x, y = 2, 7  # define range [x, y]  res = []  # list to store primes  for n in range(x, y + 1):     if n <= 1:         continue  # skip non-primes <= 1      is_prime = True  # assume n is prime     for i in range(2, int(n ** 0.5) + 1):         if n % i == 0:             is_prime = False  # n is not prime             break      if is_prime:         res.append(n)  # add prime number  print(res if res else "No") 

Output
[2, 3, 5, 7] 

Explanation: For each number n in the range, it checks if n is greater than 1. It then assumes n is prime and checks divisibility from 2 to √n. If n is divisible by any number in this range, it is marked as non-prime. If no divisors are found, n is added to the result list.

Using sympy library

SymPy Library provides a built-in function called primerange(x, y) to generate prime numbers in a given range efficiently. It is the most convenient and requires minimal coding effort. Internally, SymPy uses optimized algorithms, including the sieve method. This is ideal when you need a quick and accurate solution without implementing the logic manually.

Python
from sympy import primerange   x, y = 2, 7  # range [x, y]  primes = list(primerange(x, y + 1)) print(primes if primes else "No") 

Output

[2, 3, 5, 7]

Explanation: sympy module, which generates prime numbers in a given range. The range is defined as [x, y] and primerange(x, y + 1) returns an iterator of prime numbers from x to y. The result is converted into a list and stored in primes.

Using naive approach

Naive Approach checks for primality by dividing each number from 2 to n//2. If any divisor is found, the number is not prime. This method is the least efficient and suitable only for small intervals . It is primarily used for understanding the basic concept of prime number checking.

Python
x, y = 2, 7  # range [x, y] res = []  # list to store primes  for i in range(x, y + 1):     if i <= 1:         continue  # skip non-primes <= 1     for j in range(2, i // 2 + 1):         if i % j == 0:             break  # not a prime     else:         res.append(i)  # prime found  print(res if res else "No") 

Output
[2, 3, 5, 7] 

Explanation: It loops through each number i from x to y and checks if i is a prime. If i is less than or equal to 1, it is skipped because primes are greater than 1. For each number i, it divides i by all numbers from 2 to i // 2. If any divisor is found, the loop breaks, indicating i is not prime. If no divisor is found, the else block runs, appending i to the result list.



Next Article
Python Program to print all the numbers divisible by 3 and 5 for a given number

S

Shivam_k
Improve
Article Tags :
  • DSA
  • Python
  • Python Programs
  • Prime Number
  • python
Practice Tags :
  • Prime Number
  • python
  • python

Similar Reads

  • Print Numbers in an Interval - Python
    In this article, we are going to learn how to print numbers within a given interval in Python using simple loops, list comprehensions, and step-based ranges. For Example: Input : i = 2, j = 5Output : 2 3 4 5 Input : i = 10, j = 20 , s = 2Output : 10 12 14 16 18 20 Let’s explore different methods to
    2 min read
  • Python program to print all positive numbers in a range
    In this article, we will explore various methods to print all positive numbers in a range. The simplest way to do this is by using a loop. Use a simple for loop to iterate through the given range and check if each number is greater than zero before printing it. [GFGTABS] Python start = -5 end = 3 #
    2 min read
  • Python Program to Print All Pronic Numbers Between 1 and 100
    Pronic numbers are also called oblong numbers or rectangular numbers. They are produced by multiplying two successive integers. Mathematically, it can be written as n * (n + 1), where n is a positive integer. For instance, 6 is a pronic number because it equals 2 * (2 + 1). Similarly, when you multi
    2 min read
  • Python Program for Efficient program to print all prime factors of a given number
    Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be "2 2 3". And if the input number is 315, then output should be "3 3 5 7". Following are the steps to find all prime factors. 1) While n is divisible by 2, prin
    6 min read
  • Python Program to print all the numbers divisible by 3 and 5 for a given number
    Given the integer N, the task is to print all the numbers less than N, which are divisible by 3 and 5.Examples : Input : 50Output : 0 15 30 45 Input : 100Output : 0 15 30 45 60 75 90 Approach: For example, let's take N = 20 as a limit, then the program should print all numbers less than 20 which are
    2 min read
  • Python Program to Print all Integers that Aren't Divisible by Either 2 or 3
    We can input a set of integer, and check which integers in this range, beginning with 1 are not divisible by 2 or 3, by checking the remainder of the integer with 2 and 3. Example: Input: 10 Output: Numbers not divisible by 2 and 3 1 5 7 Method 1: We check if the number is not divisible by 2 and 3 u
    7 min read
  • Python Program to Reverse all Prime Numbers in Array Without Affecting Elements
    Given an array, our task is to Reverse all prime numbers in an array without affecting other elements in Python. Examples: Input : arr = {1, 2, 3, 4, 5, 6}Output : {1,5,3,4,2,6}Explanation: Prime elements in given array are 2,3,5. After reversing the modified array will be {1,5,3,4,2,6}Approach: Sta
    3 min read
  • Print all even numbers in a range - Python
    Our task is to print all even numbers within a given range. The simplest way to achieve this is by using a loop to iterate through the range and check each number for evenness. Let's explore some methods to do so. Using LoopWe can use a for loop with if conditional to check if a number is even. [GFG
    2 min read
  • Python program to print the octal value of the numbers from 1 to N
    Given a number N, the task is to write a Python program to print the octal value of the numbers from 1 to N. Examples: Approach: We will take the value of N as input.Then, we will run the for loop from 1 to N+1 and traverse each "i" through oct() function.Print each octal value.Note: The oct() funct
    4 min read
  • Python program to print the hexadecimal value of the numbers from 1 to N
    Given a number N, the task is to write a Python program to print the hexadecimal value of the numbers from 1 to N. Examples: Input: 3 Output: 1 2 3 Input: 11 Output: 1 2 3 4 5 6 7 8 9 a bApproach: We will take the value of N as input.Then, we will run the for loop from 1 to N+1 and traverse each "i"
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences