

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 −
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' ]
- Related Questions & Answers
- Finding sum of sequence upto a specified accuracy using JavaScript
- Listing all the prime numbers upto a specific number in JavaScript
- Sum all perfect cube values upto n using JavaScript
- Find all combinations that add upto given number using C++
- Prime numbers upto n - JavaScript
- Finding next prime number to a given number using JavaScript
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript
- Counting prime numbers from 2 upto the number n JavaScript
- Find all pairs that sum to a target value in JavaScript
- Finding the nth prime number in JavaScript
- All possible co-prime distinct element pairs within a range [L, R]?
- Sum of all prime numbers in JavaScript
- Finding the largest 5 digit number within the input number using JavaScript
- Finding a number, when multiplied with input number yields input number in JavaScript
- Finding all possible combinations from an array in JavaScript
Advertisements