2523. Closest Prime Numbers in Range #1401
-
2523. Closest Prime Numbers in Range Difficulty: Medium Topics: Given two positive integers
Return the positive integer array Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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
Let's implement this solution in PHP: 2523. Closest Prime Numbers in Range <?php
/**
* @param Integer $left
* @param Integer $right
* @return Integer[]
*/
function closestPrimes($left, $right) {
if ($right < 2) {
return array(-1, -1);
}
// Initialize sieve of Eratosthenes
$sieve = array_fill(0, $right + 1, true);
$sieve[0] = $sieve[1] = false;
for ($i = 2; $i * $i <= $right; $i++) {
if ($sieve[$i]) {
for ($j = $i * $i; $j <= $right; $j += $i) {
$sieve[$j] = false;
}
}
}
// Collect primes in the range [left, right]
$primes = array();
for ($i = max($left, 2); $i <= $right; $i++) {
if ($sieve[$i]) {
$primes[] = $i;
}
}
// Check if there are at least two primes
if (count($primes) < 2) {
return array(-1, -1);
}
$min_diff = PHP_INT_MAX;
$result = array();
// Find the pair with the smallest difference
for ($i = 0; $i < count($primes) - 1; $i++) {
$diff = $primes[$i + 1] - $primes[$i];
if ($diff < $min_diff) {
$min_diff = $diff;
$result = array($primes[$i], $primes[$i + 1]);
}
}
return $result;
}
// Example test cases
echo json_encode(closestPrimes(10, 19)); // Output: [11,13]
echo "\n";
echo json_encode(closestPrimes(4, 6)); // Output: [-1,-1]
?> Explanation:
This approach ensures that we efficiently generate primes and find the closest pair using optimal time and space complexity. |
Beta Was this translation helpful? Give feedback.
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
right
value. This algorithm efficiently marks non-prime numbers, allowing us to quickly identify primes within the range.