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

Problem

We need to write a JavaScript function that takes a number n and returns an array of all prime number pairs that sum to n. Both numbers in each pair must be prime numbers.

Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17, 19, 23.

Algorithm Approach

The solution involves three main steps:

  • Create a function to check if a number is prime
  • Generate all possible prime numbers up to the target number
  • Find pairs of primes that sum to the target number

Example Implementation

const num = 26;

const isPrime = (n) => {
    if (n  {
    return isPrime(a) ? a : 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, 2);  // Include 2 as it's the only even prime
    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 list = generateNumbers(num).filter(primeList);
    return calculate(num, list, []);
}

console.log("Prime pairs for", num + ":", findPrimeSum(num));

Output

Prime pairs for 26: [ '23+3', '19+7', '13+13' ]

Simplified Approach

Here's a cleaner, more straightforward implementation:

function isPrime(n) {
    if (n 

Output

Prime pairs for 10: [ [ 3, 7 ], [ 5, 5 ] ]
Prime pairs for 20: [ [ 3, 17 ], [ 7, 13 ] ]
Prime pairs for 26: [ [ 3, 23 ], [ 7, 19 ], [ 13, 13 ] ]

Key Points

  • The algorithm iterates only up to target/2 to avoid duplicate pairs
  • Special handling for 2 (the only even prime) is important
  • The isPrime function optimizes by checking only odd divisors after 2
  • Time complexity is O(n?n) due to prime checking for each number

Conclusion

Finding prime pairs that sum to a target number requires efficient prime detection and systematic pair generation. The simplified approach provides cleaner code while maintaining the same functionality for identifying all valid prime number pairs.

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

603 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements