
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Two Prime Numbers with a Specific Gap in JavaScript
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 −
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]
Advertisements