VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-find-prime-numbers-between-given-interval/

⇱ Program to find Prime Numbers Between given Interval - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find Prime Numbers Between given Interval

Last Updated : 28 May, 2026

Given two numbers m and n as interval range, the task is to find the prime numbers in between this interval.

Examples:

Input: m = 1, n = 10
Output: 2 3 5 7
Explanation : Primes in range from 1 to 10 are 2, 3, 5 and 7

Input : m = 10, n = 20
Output : 11 13 17 19
Explanation : Primes in range from 10 to 20 are 11, 13, 17 and 19

[Naive Approach] Trial Division Method - O(n*sqrt(n)) Time and O(1) Space

The simplest method to check if a number i is prime by checking every number from 2 to i-1. If the number n is divisible by any of these, it's not prime. We check if a number if prime or not in sqrt(i) time because we just check for factors from number 2 to sqrt(i). For more details Please refer to Check for Prime Number.

  • Traverse all numbers from m to n
  • For each number, check divisibility from 2 to √n
  • If no divisor is found, mark the number as prime
  • Store all prime numbers in the result list and return it

Output
2 3 5 7 

[Expected Approach] Using Sieve of Eratosthenes - O(n loglog n) Time and O(n) Space

The idea is to precompute all prime numbers up to n using the Sieve of Eratosthenes. Initially, all numbers are marked as prime, then multiples of each prime number are marked as non-prime. After preprocessing, all prime numbers in the required range [m, n] can be collected efficiently.

  • Create a boolean array and mark all numbers as prime initially
  • Starting from 2, mark all multiples of each prime number as non-prime
  • After sieve computation, traverse from m to n
  • Store and return all numbers still marked as prime

Example for n = 10
Initially:
2 3 4 5 6 7 8 9 10 -> all marked prime

Step 1: p = 2
Mark multiples of 2:
4 6 8 10 -> not prime
Remaining:
2 3 5 7 9

Step 2: p = 3
Mark multiples of 3:
9 -> not prime

Final Prime Numbers:
2 3 5 7


Output
2 3 5 7 
Comment