# Finding two prime numbers with a specific number gap in JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

We are required to write a JavaScript function that takes in a number, gap as the first argument and a range array of two numbers as the second argument. Our function should return an array of all such prime pairs that have an absolute difference of gap and falls between the specified range.

## Example

Following is the code −

Live Demo

const gap = 4;
const range = [20, 200];
const primesInRange = (gap, [left, right]) => {
const isPrime = num => {
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));

## Output

Following is the console output −

[37, 41]
Updated on 20-Apr-2021 07:25:13