2523. Closest Prime Numbers in Range
Given two positive integers
leftandright, find the two integersnum1andnum2such that:
left <= num1 < num2 <= right.- Both
num1andnum2are prime numbers.num2 - num1is the minimum amongst all other pairs satisfying the above conditions.Return the positive integer array
ans = [num1, num2]. If there are multiple pairs satisfying these conditions, return the one with the smallestnum1value. If no such numbers exist, return[-1, -1].Example 1:
Input: left = 10, right = 19
Output: [11,13]
Explanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19.
The closest gap between any pair is 2, which can be achieved by [11,13] or [17,19].
Since 11 is smaller than 17, we return the first pair.Example 2:
Input: left = 4, right = 6
Output: [-1,-1]
Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.
def isPrime(self, num):
if num < 2:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0:
return False
divisor = 3
while divisor * divisor <= num:
if num % divisor == 0:
return False
divisor += 2
return True
def closestPrimes(self, left: int, right: int) -> List[int]:
prev_prime = -1
closestA = -1
closestB = -1
min_difference = float("inf")
# Iterate over the range of numbers and find primes
for candidate in range(left, right + 1):
if self.isPrime(candidate):
if prev_prime != -1:
difference = candidate - prev_prime
if difference < min_difference:
min_difference = difference
closestA = prev_prime
closestB = candidate
if difference == 1 or difference == 2:
return [prev_prime, candidate]
prev_prime = candidate
return [closestA, closestB] if closestA != -1 else [-1, -1]