Finding two prime numbers with a specific number gap in JavaScript

Finding prime numbers with a specific gap is a common programming challenge. This involves identifying two prime numbers where their difference equals a given value within a specified range.

Problem

We need to write a JavaScript function that takes a gap number and a range array as arguments. The function should return the first pair of prime numbers that have an absolute difference equal to the gap and fall within the specified range.

Algorithm Approach

The solution involves two main steps:

  • Find all prime numbers within the given range
  • Search for consecutive primes with the specified gap

Implementation

const gap = 4;
const range = [20, 200];

const primesInRange = (gap, [left, right]) => {
    const isPrime = num => {
        if (num < 2) return false;
        for(let i = 2; i < num; i++){
            if(num % i === 0){
                return false;
            }
        }
        return true;
    };
    
    const primes = [];
    const res = [];
    
    for(let i = left; i < right; i++){
        if(isPrime(i)){
            primes.push(i);
        }
    }
    
    let currentNum = primes[0];
    for(let j = 1; j < primes.length; j++){
        if(primes[j] - currentNum === gap){
            res.push(currentNum, primes[j]);
            return res;
        } else {
            currentNum = primes[j];
        }
    }
    return null;
};

console.log(primesInRange(gap, range));
[37, 41]

How It Works

The isPrime helper function checks if a number is prime by testing divisibility from 2 to the number itself. The main function first collects all primes in the range, then iterates through them to find the first pair with the specified gap.

Example with Different Gap

// Finding prime pairs with gap of 2 (twin primes)
const gap2 = 2;
const range2 = [10, 50];

console.log(primesInRange(gap2, range2));
[11, 13]

Key Points

  • The function returns the first pair found with the specified gap
  • Returns null if no such pair exists in the range
  • The prime checking algorithm can be optimized for larger ranges
  • Twin primes (gap = 2) are the most common case

Conclusion

This solution efficiently finds prime pairs with specific gaps by first generating all primes in range, then searching for the required difference. The approach works well for moderate ranges and can be optimized further for larger datasets.

Updated on: 2026-03-15T23:19:00+05:30

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements