Skip to content

2523. Closest Prime Numbers in Range #1401

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to find the two closest prime numbers within a given range [left, right]. If there are multiple pairs with the same minimum difference, we return the pair with the smallest starting prime. If there are fewer than two primes in the range, we return [-1, -1].

Approach

  1. Generate Primes Efficiently: Use the Sieve of Eratosthenes algorithm to generate all prime numbers up to the given right value. This algorithm efficiently marks non-prime numbers, allowing us to quickly identify primes within the range.
  2. Collect Primes in Range: Extract all prime numbers from the generated sieve that lie within the range [left, right].
  3. Find Closest Primes: Iterate through the collected primes and compu…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Mar 7, 2025
Maintainer Author

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Mar 7, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants