Find three prime numbers with given sum

Given an integer N, the task is to find three prime numbers X, Y and Z such that the sum of these three numbers is equal to N i.e. X + Y + Z = N.

Examples:

Input: N = 20
Output: 2 5 13

Input: N = 34
Output: 2 3 29

Approach:



  • Generate prime numbers using Sieve of Eratosthenes
  • Start from the first prime number.
  • Take another number from the generated list.
  • Subtract first number and second number from the original number to obtain the third number.
  • Check if the third number is a prime number.
  • If the third number is a prime number then output the three numbers.
  • Otherwise, repeat the process for the second number and consequently the first number
  • If the answer does not exist then print -1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
  
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100001;
  
// The vector primes holds
// the prime numbers
vector<int> primes;
  
// Function to generate prime numbers
void initialize()
{
  
    // Initialize the array elements to 0s
    bool numbers[MAX] = {};
    int n = MAX;
    for (int i = 2; i * i <= n; i++)
        if (!numbers[i])
            for (int j = i * i; j <= n; j += i)
  
                // Set the non-primes to true
                numbers[j] = true;
  
    // Fill the vector primes with prime
    // numbers which are marked as false
    // in the numbers array
    for (int i = 2; i <= n; i++)
        if (numbers[i] == false)
            primes.push_back(i);
}
  
// Function to print three prime numbers
// which sum up to the number N
void findNums(int num)
{
  
    bool ans = false;
    int first = -1, second = -1, third = -1;
    for (int i = 0; i < num; i++) {
  
        // Take the first prime number
        first = primes[i];
        for (int j = 0; j < num; j++) {
  
            // Take the second prime number
            second = primes[j];
  
            // Subtract the two prime numbers
            // from the N to obtain the third number
            third = num - first - second;
  
            // If the third number is prime
            if (binary_search(primes.begin(),
                              primes.end(), third)) {
                ans = true;
                break;
            }
        }
        if (ans)
            break;
    }
    // Print the three prime numbers
    // if the solution exists
    if (ans)
        cout << first << " "
             << second << " " << third << endl;
    else
        cout << -1 << endl;
}
  
// Driver code
int main()
{
    int n = 101;
  
    // Function for generating prime numbers
    // using Sieve of Eratosthenes
    initialize();
  
    // Function to print the three prime
    // numbers whose sum is equal to N
    findNums(n);
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
from math import sqrt
  
MAX = 100001
  
# The vector primes holds 
# the prime numbers 
primes = []; 
  
# Function to generate prime numbers 
def initialize() :
  
    # Initialize the array elements to 0s 
    numbers = [0]*(MAX + 1);
    n = MAX
    for i in range(2, int(sqrt(n)) + 1) : 
        if (not numbers[i]) :
            for j in range( i * i , n + 1, i) : 
  
                # Set the non-primes to true 
                numbers[j] = True
  
    # Fill the vector primes with prime 
    # numbers which are marked as false 
    # in the numbers array 
    for i in range(2, n + 1) :
        if (numbers[i] == False) :
            primes.append(i); 
  
# Function to print three prime numbers 
# which sum up to the number N 
def findNums(num) : 
  
    ans = False
    first = -1
    second = -1;
    third = -1
    for i in range(num) :
  
        # Take the first prime number 
        first = primes[i]; 
        for j in range(num) :
  
            # Take the second prime number 
            second = primes[j]; 
  
            # Subtract the two prime numbers 
            # from the N to obtain the third number 
            third = num - first - second; 
  
            # If the third number is prime 
            if (third in primes) :
                ans = True
                break
      
        if (ans) :
            break
      
    # Print the three prime numbers 
    # if the solution exists 
    if (ans) :
        print(first , second , third); 
    else :
        print(-1); 
  
# Driver code 
if __name__ == "__main__"
  
    n = 101
  
    # Function for generating prime numbers 
    # using Sieve of Eratosthenes 
    initialize(); 
  
    # Function to print the three prime 
    # numbers whose sum is equal to N 
    findNums(n); 
  
# This code is contributed by AnkitRai01

chevron_right


Output:

2 2 97

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnkitRai01