VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-difference-between-any-two-primes-from-the-given-range/

⇱ Minimum difference between any two primes from the given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum difference between any two primes from the given range

Last Updated : 12 Jul, 2025

Given two integers L and R, the task is to find the minimum difference between any two prime numbers in the range [L, R].

Examples: 

Input: L = 21, R = 50 
Output:
(29, 31) and (41, 43) are the only valid pairs 
that give the minimum difference.

Input: L = 1, R = 11 
Output:
The difference between (2, 3) is minimum. 
 

Approach:  

  • Find all the prime numbers upto R using Sieve of Eratosthenes.
  • Now starting from L, find the difference between any two prime numbers within the range and update minimum difference so far.
  • If the number of primes in the range were < 2 then print -1.
  • Else print the minimum difference.

Below is the implementation of the above approach:  


Output: 
2

 

Time Complexity: O((R - L) + sqrt(105))

Auxiliary Space: O(105)

Comment