š Finding the Closest Prime Numbers in a Range using the Sieve of Eratosthenes (leetcode - 2523)
š Finding the Closest Prime Numbers in a Range using the Sieve of Eratosthenes
Prime numbers play a crucial role in number theory and various computational applications. In this blog, we will explore an optimized approach to finding the two closest prime numbers within a given range using the Sieve of Eratosthenes. š
š Problem Statement
Given two integers left
and right
, find the two
prime numbers within the range [left, right]
that have the
smallest difference. If there are fewer than two prime numbers, return
[-1, -1]
.
š ️ Approach
To efficiently solve this problem, we use the
Sieve of Eratosthenes algorithm to precompute prime numbers
up to right
. Then, we extract the prime numbers from the given
range and find the closest pair.
✅ Steps to Solve
-
Initialize a boolean list
primes
whereprimes[i] = True
indicatesi
is prime. -
Mark
0
and1
asFalse
(not prime). - Use the Sieve of Eratosthenes to eliminate non-prime numbers.
-
Extract prime numbers from the given range
[left, right]
. - Iterate through the primes to find the pair with the smallest difference.
-
Return the closest prime pair or
[-1, -1]
if there are fewer than two primes.
š Code Implementation
from typing import List
class Solution:
def closestPrimes(self, left: int, right: int) -> List[int]:
# Sieve of Eratosthenes
primes = [True] * (right + 1)
primes[0], primes[1] = False, False
for i in range(2, int(right * 0.5) + 1):
if primes[i]:
for j in range(i * i, right + 1, i):
primes[j] = False
# find primes from the given range
primes_range = [i for i in range(left, right + 1) if primes[i]]
# length of prime numbers
n = len(primes_range)
closest_pair = [-1, -1]
# check the length
if n < 2:
return closest_pair
# maximum value
min_dif = float('inf')
# checking for minimum difference
for i in range(n - 1):
dif = primes_range[i + 1] - primes_range[i]
if dif < min_dif:
min_dif = dif
closest_pair = [primes_range[i], primes_range[i + 1]]
# return the final value
return closest_pair
⏳ Complexity Analysis
- Sieve of Eratosthenes:
O(N log log N)
- Extracting primes in the range:
O(N)
-
Finding the closest pair:
O(K)
(whereK
is the number of primes in range) - Overall Complexity:
O(N log log N)
š Example Walkthrough
Input:
left = 10, right = 50
Output:
[11, 13]
Explanation:
Primes in range [10, 50]
:
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
. The closest pair
is (11, 13)
with a difference of 2
.
š Conclusion
The Sieve of Eratosthenes provides an efficient way to
compute prime numbers, making this approach optimal for large values of
right
. By leveraging this algorithm, we can quickly find the
closest prime numbers in a given range.
Hope you found this useful! Happy coding! šÆ
Comments
Post a Comment