Open In App

Find two prime numbers with given sum

Last Updated : 04 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an even number n (greater than 2), the task is to find two prime numbers whose sum will be equal to the given number. Note: There are several combinations possible, find only the pair whose minimum value is the smallest among all the minimum values of pairs and print the minimum element first. The solution will always exist according to Goldbach’s conjecture.

Examples

Input: n = 74
Output: 3 71
Explanation: There are several possibilities like 37 37. But the minimum value of this pair is 3 which is the smallest among all possible minimum values of all the pairs.

Input: n = 4
Output: 2 2
Explaination: This is the only possible partitioning of 4.

Approach:

The idea is to use the Sieve of Eratosthenes to find all prime numbers up to n. Then, we iterate through numbers from 2 to n/2, checking if both the number and its complement (i.e., n - number) are prime. The first valid pair of primes whose sum equals n is returned, ensuring the smallest prime pair is selected.

C++
// C++ code to find two primes whose sum
// equals given even number
#include <bits/stdc++.h>
using namespace std;

// Function to generate primes up to n 
// using Sieve of Eratosthenes
vector<bool> sieve(int n) {
  
    // Initialize all as prime
    vector<bool> isPrime(n + 1, true); 
  
    // 0 and 1 are not primes
    isPrime[0] = isPrime[1] = false;  

    // Mark non-primes using multiples of each prime
    for (int i = 2; i * i <= n; i++) {
        if (isPrime[i]) {
            for (int j = i * i; j <= n; j += i) {
                isPrime[j] = false; 
            }
        }
    }
    return isPrime; 
}

// Function to find two primes whose sum equals n
vector<int> primeDivision(int n) {
  
    // Get all primes up to n
    vector<bool> isPrime = sieve(n); 

    // Iterate to find the smallest pair
    for (int i = 2; i <= n / 2; i++) {
        if (isPrime[i] && isPrime[n - i]) {
            return {i, n - i}; 
        }
    }
  
    // Return empty if no pair found (won't occur)
    return {}; 
}

int main() {
    
    int n = 74; 
    vector<int> result = primeDivision(n);

    cout << result[0] << " " << result[1];
 
    return 0;
}
Java
// Java code to find two primes whose sum 
// equals given even number
import java.util.*;

class GfG {

    // Function to generate primes up to n 
    // using Sieve of Eratosthenes
    static boolean[] sieve(int n) {
        
        // Initialize all as prime
        boolean[] isPrime = new boolean[n + 1]; 
        Arrays.fill(isPrime, true); 
        
        // 0 and 1 are not primes
        isPrime[0] = isPrime[1] = false;  

        // Mark non-primes using multiples of each prime
        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                for (int j = i * i; j <= n; j += i) {
                    isPrime[j] = false; 
                }
            }
        }
        return isPrime; 
    }

    // Function to find two primes whose sum equals n
    static List<Integer> primeDivision(int n) {
        
        // Get all primes up to n
        boolean[] isPrime = sieve(n); 

        // Iterate to find the smallest pair
        for (int i = 2; i <= n / 2; i++) {
            if (isPrime[i] && isPrime[n - i]) {
                return Arrays.asList(i, n - i); 
            }
        }
        
        // Return empty list if no pair found (won't occur)
        return new ArrayList<>(); 
    }

    public static void main(String[] args) {
      
        int n = 74; 
        List<Integer> result = primeDivision(n);

        System.out.print(result.get(0) + " " + result.get(1));
    }
}
Python
# Python code to find two primes whose sum 
# equals given even number

# Function to generate primes up to n 
# using Sieve of Eratosthenes
def sieve(n):
  
    # Initialize all as prime
    isPrime = [True] * (n + 1)

    # 0 and 1 are not primes
    isPrime[0] = isPrime[1] = False  

    # Mark non-primes using multiples of each prime
    for i in range(2, int(n**0.5) + 1):
        if isPrime[i]:
            for j in range(i * i, n + 1, i):
                isPrime[j] = False
    return isPrime

# Function to find two primes whose sum equals n
def primeDivision(n):
  
    # Get all primes up to n
    isPrime = sieve(n)

    # Iterate to find the smallest pair
    for i in range(2, n // 2 + 1):
        if isPrime[i] and isPrime[n - i]:
            return [i, n - i]

    # Return empty list if no pair found (won't occur)
    return []
  
if __name__ == '__main__':

    n = 74
    result = primeDivision(n)
    
    print(result[0], result[1])
C#
// C# code to find two primes whose sum 
// equals given even number
using System;
using System.Collections.Generic;

class GfG {
    
    // Function to generate primes up to n 
    // using Sieve of Eratosthenes
    static bool[] Sieve(int n) {
        
        // Initialize all as prime
        bool[] isPrime = new bool[n + 1]; 
        Array.Fill(isPrime, true); 
        
        // 0 and 1 are not primes
        isPrime[0] = isPrime[1] = false;  

        // Mark non-primes using multiples of each prime
        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                for (int j = i * i; j <= n; j += i) {
                    isPrime[j] = false; 
                }
            }
        }
        return isPrime; 
    }

    // Function to find two primes whose sum equals n
    static List<int> PrimeDivision(int n) {
        
        // Get all primes up to n
        bool[] isPrime = Sieve(n); 

        // Iterate to find the smallest pair
        for (int i = 2; i <= n / 2; i++) {
            if (isPrime[i] && isPrime[n - i]) {
                return new List<int> { i, n - i }; 
            }
        }
        
        // Return empty list if no pair found (won't occur)
        return new List<int>(); 
    }

    static void Main(string[] args) {
      
        int n = 74; 
        List<int> result = PrimeDivision(n);

        Console.WriteLine(result[0] + " " + result[1]);
    }
}
JavaScript
// Javascript code to find two primes whose sum 
// equals given even number

// Function to generate primes up to n 
// using Sieve of Eratosthenes
function sieve(n) {

    // Initialize all as prime
    let isPrime = Array(n + 1).fill(true);

    // 0 and 1 are not primes
    isPrime[0] = isPrime[1] = false;

    // Mark non-primes using multiples of each prime
    for (let i = 2; i * i <= n; i++) {
        if (isPrime[i]) {
            for (let j = i * i; j <= n; j += i) {
                isPrime[j] = false;
            }
        }
    }
    return isPrime;
}

// Function to find two primes whose sum equals n
function primeDivision(n) {

    // Get all primes up to n
    const isPrime = sieve(n);

    // Iterate to find the smallest pair
    for (let i = 2; i <= n / 2; i++) {
        if (isPrime[i] && isPrime[n - i]) {
            return [i, n - i];
        }
    }

    // Return empty array if no pair found (won't occur)
    return [];
}

const n = 74;
const result = primeDivision(n);

console.log(result[0], result[1]);

Output
3 71

Time Complexity: O(n * log(log(n))), due to the Sieve of Eratosthenes, followed by a linear scan to find the pair.
Auxiliary Space: O(n), for the array used to store prime numbers up to n.


Next Article

Similar Reads