Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 7, 2025 21:15
Show Gist options
  • Save tatsuyax25/5392e398b0337cb5906578939137ec73 to your computer and use it in GitHub Desktop.
Save tatsuyax25/5392e398b0337cb5906578939137ec73 to your computer and use it in GitHub Desktop.
Given two positive integers left and right, find the two integers num1 and num2 such that: left <= num1 < num2 <= right . Both num1 and num2 are prime numbers. num2 - num1 is the minimum amongst all other pairs satisfying the above conditions. Retur
/**
* @param {number} left
* @param {number} right
* @return {number[]}
*/
// Function to check if a number is prime
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) return false;
}
return true;
};
// Function to find the closest pair of prime numbers within the given range
var closestPrimes = function(left, right) {
let primes = [];
// Generate all primes in the range [left, right]
for (let num = left; num <= right; num++) {
if (isPrime(num)) {
primes.push(num);
}
}
// If less than 2 primes are found, return [-1, -1]
if (primes.length < 2) {
return [-1, -1];
}
// Variables to store the minimum difference and the closest pair
let minDiff = Infinity;
let closestPair = [-1, -1];
// Iterate through the primes and find the pair with the smallest difference
for (let i = 0; i < primes.length - 1; i++) {
let diff = primes[i + 1] - primes[i];
if (diff < minDiff) {
minDiff = diff;
closestPair = [primes[i], primes[i + 1]];
}
}
return closestPair;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment