Given two integers L and R, the task is to find the minimum difference between any two prime numbers in the range [L, R].
Input: L = 21, R = 50
(29, 31) and (41, 43) are the only valid pairs
that give the minimum difference.
Input: L = 1, R = 11
The difference between (2, 3) is minimum.
- 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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range
- Count primes that can be expressed as sum of two consecutive primes and 1
- Count of primes below N which can be expressed as the sum of two primes
- Length of largest sub-array having primes strictly greater than non-primes
- Minimum window size containing atleast P primes in every window of given range
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Sum of all Primes in a given range using Sieve of Eratosthenes
- Count of primes in a given range that can be expressed as sum of perfect squares
- Find minimum difference between any two elements
- Find minimum difference between any two elements | Set 2
- Remove Minimum coins such that absolute difference between any two piles is less than K
- Place the prisoners into cells to maximize the minimum difference between any two
- Check if the sum of primes is divisible by any prime from the array
- Minimum operations required to convert X to Y by multiplying X with the given co-primes
- Program for Goldbach’s Conjecture (Two Primes with given Sum)
- Difference between the largest and the smallest primes in an array
- Segmented Sieve (Print Primes in a Range)
- K-Primes (Numbers with k prime factors) in a range
- Product of all primes in the range from L to R
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.