Finding all possible prime pairs that sum upto input number using JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Our function should return an array of all such number pairs that when summed are n and both of them are prime.

Example

Following is the code −

 Live Demo

const num = 26;
const isPrime = (n) => {
   if (n % 2 === 0) return false;
   let sqrtn = Math.sqrt(n)+1;
   for (let i=3; i < sqrtn; i+=2) {
      if (n % i === 0) return false;
   }
   return true;
}
const primeList = (a) => {
   if (isPrime(a)) return a; else return false;
};
const generateNumbers = (n) => {
   let num = (n % 2 === 0) ? (n -1) : n;
   let list = []
   for (let i = num; i > 3; i-=2)
      list.push(i);
   list.push(3,1);
   return list;
}
const calculate = (num, list, results) => {
   if (list.length === 0) return results;
      let item = list.shift();
   let itemPairIndex = list.indexOf(num - item);
   if (itemPairIndex !== -1) {
      let itemPair = list.splice(itemPairIndex,1)
      results.push(item+"+"+itemPair);
   }
   return calculate(num, list, results);
}
const findprimeSum = (num) => {
   const pairs = [];
   const list = generateNumbers(num).filter(primeList);
   return calculate(num, list, []);
}
console.log(findprimeSum(num));

Output

[ '23+3', '19+7' ]

Updated on: 19-Apr-2021

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements